/*
思路:建立hashmap 储存s中每个字母在string中最后的位置;
然后遍历string 找到 当前字母的最后位置存到temp 如果在后续遍历的过程中 大于temp 则更新temp 一直到i = temp 此时能得到一个partition,
辅助需要 start tamp 两个位置变量 用于得到partition的长度;
*/
class Solution {
public List<Integer> partitionLabels(String S) {
List<Integer> result = new ArrayList<>();
int start = 0, temp = 0;
HashMap<Character, Integer> map = new HashMap<>();
char[] cs = S.toCharArray();
for(int i = 0; i < cs.length; i++) {
map.put(cs[i], i);
}
for(int i = 0; i < cs.length; i++) {
temp = map.get(cs[i]) > temp ? map.get(cs[i]) : temp;
if(i == temp) {
result.add(temp - start + 1);
start = i + 1;
temp = i + 1;
}
}
return result;
}
}
Partition Labels java leetcode 走地牙
最新推荐文章于 2021-12-11 17:44:29 发布