leetcode第763题划分字母区间
**实话:**不看题解根本做不出来,一看题解,好巧妙啊!我真的是蠢货。
思路:
- 找出每个字母最迟对应的下标,放在对应的hash表中,
- 最大范围覆盖,如果中间发现还有比这个字母靠后的,分割,继续往后走,贪心是在这里体现的。找最后的值对应。
class Solution {
public List<Integer> partitionLabels(String s) {
// 贪心的思路是真的不好想
int[] edge = new int[27];
char[] chars = s.toCharArray();
for(int i = 0;i < s.length();i++){
edge[chars[i] - 'a'] = i;
}
//其实就还是挑选最大的那个
LinkedList<Integer> list = new LinkedList<>();
int last = -1;
int left = 0;
int right = 0;
for(int i = 0;i < chars.length;i++){
right = Math.max(right,edge[chars[i] - 'a']);
if(i == right){
list.add(right - left + 1);
left = i+1;
}
}
return list;
}
}