维护一个窗口,如果当前字母出现的最后一次的位置(last)比右边界大,那么需要拓展窗口,当 i 与 j 相遇的时候,说明窗口内部所有的字母都符合条件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public List<Integer> partitionLabels(String S){ int[] last = newint[26]; for (int i = 0; i < S.length(); ++i) last[S.charAt(i) - 'a'] = i; int j = 0//右窗口; int anchor = 0//左窗口; List<Integer> ans = new ArrayList(); for (int i = 0; i < S.length(); ++i) { j = Math.max(j, last[S.charAt(i) - 'a']); if (i == j) { ans.add(j - anchor + 1); anchor = i + 1; } } return ans; }