分隔字符串使同种字符出现在一起
763. Partition Labels (Medium)
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
解法:第一个for循环,以26个英文字母的数组依次遍历整个S,记录S中每个字符出现的次数,存到对应的位置;
之后我们要考虑怎么分割这个S了,看上面的例子第一个字符最后出现的位置是9 第二个字符出现的是6 定义一个指针index,
index不断增加 每遍历一个S中的字符就记录下这个字符最后出现的位置,定义一个lastIndex,记录前i个字符中,最后出现位置
最大的值,这个最大值如果和i相同了, 说明前i个字符都不再后面出现 可以分割了
这里由于firstIndex引入这是为了计算差值,此处等于-1;
class Solution {
public List<Integer> partitionLabels(String S) {
int[] lastIndexOfChar = new int[26];
for(int i=0; i < S.length(); i++){
lastIndexOfChar[S.charAt(i) - 'a'] = i;
}
int LastIndex = 0;
int firstIndex = -1;
List<Integer> str = new ArrayList<>();
for(int i=0; i < S.length(); i++){
int index = lastIndexOfChar[S.charAt(i) - 'a'];
LastIndex = Math.max(index, LastIndex);
if(LastIndex == i){
str.add(LastIndex - firstIndex);
firstIndex = LastIndex;
}
}
return str;
}
}