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.
思路:扫两遍,第一遍记录每个char的最后的位置,第二次,看char的最后位置是否比maxend大,如果大就更新,否则如果i == maxend表明,从start到maxend是个 一个valid string,然后start = i + 1 以此类推;
主要是记录最后一个char比较难想,然后更新最后的maxend也比较难点,其余就是two pointer的想法;
class Solution {
public List<Integer> partitionLabels(String S) {
List<Integer> list = new ArrayList<Integer>();
if(S == null || S.length() == 0) {
return list;
}
HashMap<Character, Integer> hashmap = new HashMap<>();
for(int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
// store last position of this char;
hashmap.put(c, i);
}
int start = 0;
int maxend = 0;
for(int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
if(hashmap.get(c) > maxend) {
maxend = hashmap.get(c);
}
if(i == maxend) {
list.add(maxend - start + 1);
maxend = 0;
start = i + 1;
}
}
return list;
}
}