方法一:滑动窗口
class Solution { public List<Integer> partitionLabels(String s) { List<Integer> res = new ArrayList<>(); int[] arr = new int[128]; for(char c : s.toCharArray()) { arr[c]++; } int[] window = new int[128]; int n = s.length(), i = 0, j = 0, sumChar = 0, count = 0; while(j < n) { char c = s.charAt(j++); if(window[c] == 0) sumChar++; if(++window[c] == arr[c]) count++; if(sumChar == count) { res.add(j - i); i = j; sumChar = 0; count = 0; } } return res; } }
方法二:贪心,考虑好每个字符的最远出现位置
class Solution { public List<Integer> partitionLabels(String s) { List<Integer> res = new ArrayList<>(); int[] arr = new int[26]; // 存储每个字符最后一个位置 for(int i = 0; i < s.length(); i++) { arr[s.charAt(i)-'a'] = i; } int start = 0, j = 0; for(int i = 0; i < s.length(); i++) { j = Math.max(j,arr[s.charAt(i)-'a']);// j为当前遍历字符的最远的位置 if(i == j) { // 当前包含所有已遍历字符就可以加入 res.add(i - start + 1); start = i + 1; } } return res; } }