763. Partition Labels
A string S
of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
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.
Note:
S
will have length in range[1, 500]
.S
will consist of lowercase letters ('a'
to'z'
) only.
解题要点:
先遍历一次,把每个字母最后出现的index记录下来。然后从第一位开始找它最后出现的位置,加到返回值里,并将起始值更新为这个位置的后一位,继续寻找。
class Solution {
public List<Integer> partitionLabels(String S) {
int[] lastIndex = new int[26];
for(int i = 0; i < S.length(); i++){
lastIndex[S.charAt(i) - 'a'] = i;
}
List<Integer> res = new ArrayList<>();
int index1 = 0;
while(index1 < S.length()){
int index2 = index1;
for(int i = index1; i < S.length() && i <= index2; i++){
int index = lastIndex[S.charAt(i) - 'a'];
index2 = Math.max(index, index2);
}
res.add(index2 - index1 + 1);
index1 = index2 + 1;
}
return res;
}
}
Last updated
Was this helpful?