【c++】leetcode763 划分字母区间
1.题目
题目分析:
①同一个字符只能出现在一个片段中
②划分成尽可能多的片段
2.code
思路:
①先把所有出现过的字符个数进行统计
②通过滑窗与快慢指针以及一个valid==windows.size()说明目前为止(fast)出现过的字符都已经全部出现过了,即不在其他的片段中
class Solution {
public:vector<int> partitionLabels(string s) {unordered_map<char, int> t, window;std::vector<int> res{};int slow = 0, fast = 0, valid = 0;for (auto i = 0; i < s.length(); i++){if (t.count(s[i]) == 0) t[s[i]] = 0;t[s[i]]++;}while (fast < s.length()){if (t.count(s[fast])){window[s[fast]]++;if (window[s[fast]] == t[s[fast]]) valid++;}if (valid == window.size()){if (fast - slow < s.length()){res.push_back(fast - slow + 1);slow = fast + 1;}}fast++;}return res;}
};
截止到2025.7.30日,所有的case可以AC。