【leetcode hot 100 763】划分字母区间

发布于:2025-04-08 ⋅ 阅读:(40) ⋅ 点赞:(0)

解法一:用map记录<字母,字母出现的次数>,循环取出value-1,每次判断已经取出的字母(Set记录)是否还在后面存在(value>1),若存在继续循环,若不存在开启下一循环(再找新的一串字母)

import java.util.*;

/**
 * @author longyy
 * @version 1.0
 */
class Solution79 {
    public List<Integer> partitionLabels(String s) {
        List<Integer> result = new ArrayList<>();
        if (s == null || s.length() == 0) return result;
        int n = s.length();
        Map<Character, Integer> has = new HashMap<>();
        for (int i = 0; i < n; i++) {
            if(has.containsKey(s.charAt(i))) {
                has.put(s.charAt(i), has.get(s.charAt(i))+1);
            }
            else {
                has.put(s.charAt(i), 1);
            }
        }

        int num =0;
        Set<Character> curr = new HashSet<>();
        int i=0;
        while(i<n) {
            curr.add(s.charAt(i));
            num++;
            has.put(s.charAt(i), has.get(s.charAt(i))-1);
            boolean isEnd = true;
            for(char c : curr) {
                if(has.get(c)>0){
                    // 后面还有,还没取完
                    isEnd = false;
                    break;
                }
            }
            if(isEnd){
                result.add(num);
                curr.clear();
                num=0;
            }
            i++;
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        Solution79 sol = new Solution79();
        System.out.println(sol.partitionLabels(s));
    }
}

注意:

  • 加入list时,不能result.add(set.size()),这个size是不重复的字母个数,要result.add(num)