Timeline
Timeline
2026-03-20
init
Greedy
Problem:
BFS approach:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 | using std::vector;using std::string;using std::queue;class Solution { public: vector<int> partitionLabels(string s) { // 1 <= s.length <= 500 // s consists of lowercase English letters only. int i, n = s.size(); int start = 0; vector<int> res; vector<int> last_showed_pos(26, -1); for (i = n - 1; i >= 0; i--) { // The position of the last occurrence of each letter if (last_showed_pos[s[i] - 'a'] == -1) last_showed_pos[s[i] - 'a'] = i; } while (start < n) { queue<char> que; vector<bool> visited(26, false); int len = 0; que.push(s[start]); visited[s[start] - 'a'] = true; while (!que.empty()) { char ch = que.front(); que.pop(); int boundary = last_showed_pos[ch - 'a']; len = std::max(len, boundary - start + 1); for (i = 0; i <= boundary; i++) { if (!visited[s[i] - 'a']) { que.push(s[i]); visited[s[i] - 'a'] = true; } } } res.push_back(len); start = start + len; } return res; }}; |
