【贪心+排序】763. 划分字母区间(其实不用排序)
思路:记录字符串s中每个字母出现的最右边的位置(如果要记录左侧位置,则需要排序,这里可以不用),然后遍历字符串,记录left和right两个下标,
left:区间的左边界;
right:区间的右边界;
如果当前遍历的字符的最右边位置大于等于右边界,则更新右边界,如果当前遍历的下标大于右边界,则将left和right放入结果中,并更新left和right。
class Solution {
public:
vector<int> partitionLabels(string s) {
int len = s.size();
int ch_dict[26];
for(int i=0;i<26;++i)
ch_dict[i] = -1;
for(int i=0;i<len;++i)
ch_dict[s[i]-'a'] = i; // KEY!!!优化
vector<int> result;
int left = 0, right = ch_dict[s[0]-'a'];
ch_dict[s[0]-'a'] = -1;
for(int i=1;i<len;++i)
if(ch_dict[s[i]-'a'] != -1){
if(i > right){
result.push_back(right - left + 1);
left = i;
right = ch_dict[s[i]-'a'];
}
else if(ch_dict[s[i]-'a'] > right)
right = ch_dict[s[i]-'a'];
ch_dict[s[i]-'a'] = -1;
}
result.push_back(right - left + 1);
return result;
}
};