leetcode-贪心-763. 划分字母区间
class Solution { public: vector<int> partitionLabels(string s) { vector<int> res; int map[26]; for(int i = 0; i < s.length(); i++){ map[s[i]-'a'] = i; // 记录每个单词最后出现的位置 } int start =0, end =0; for(int i = 0; i < s.length(); i++){ end = max(end, map[s[i]-'a']); // 每一次更新单词最远出现的位置 if(i==end){ // 此区间形成闭环,可以划分 res.push_back(end-start+1); start = end+1; // 更新下一个区间起始位置 } } return res; } };
class Solution { public: vector<int> partitionLabels(string s) { vector<int> res; unordered_map<char, int> un_map; for(int i = 0; i < s.size(); i++){ un_map[s[i]] = i; // 记录每个字母最后出现的位置 } int i = 0; int j = 0; int maxindex = -1; while(i<s.size()&&j<s.size()){ // 更新字母最远出现的位置 maxindex = max(maxindex, un_map[s[j]]); if(j == maxindex){ // 如果下标等于字母最后出现的位置 ,说明行程闭环 res.push_back(j-i+1); j++; i = j; }else{ j++; } } return res; } };