diff --git a/OJ notes/pages/Leetcode Partition-Labels.md b/OJ notes/pages/Leetcode Partition-Labels.md index ab1cdb2..6e94b1d 100644 --- a/OJ notes/pages/Leetcode Partition-Labels.md +++ b/OJ notes/pages/Leetcode Partition-Labels.md @@ -16,7 +16,7 @@ > > ##### Additional tags: > -> #leetcode +> #leetcode #CS_list_need_practicing > > ##### Revisions: > @@ -57,6 +57,70 @@ A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits ### Thoughts > [!summary] -> This is a #template_remove_me +> This is a #greedy problem. + +#### Why is it a greedy problem? + +Consider this situation: +``` +s: ababc +partition: abab|c +``` + +Note that, for every appearance `ch`, it has be in one +interval. + +``` +ababc +|-| + |-| + | +``` + +if the interval for a element `b` is bigger than `a`, +merge it. + +``` +acdcdabb +|----| + |-| + | + || +``` + +We have to make interval from one side of string to another, +to save space and do it efficiently. ### Solution + +```cpp +class Solution { +public: + vector partitionLabels(string s) { + // greedy hash table, O(N) + + // We don't have to init values, as every element in + // s must have a value here. + vector last(26); + + int segEnd = 0, segStart = 0; + + vector ans; + + for (int i = 0, size = s.size(); i < size; i++) { + last[s[i] - 'a'] = i; + } + + for (int i = 0, size = s.size(); i < size; i++) { + segEnd = max(segEnd, last[s[i] - 'a']); + + if (i == segEnd) { + ans.push_back(segEnd - segStart + 1); + segStart = segEnd + 1; + } + } + + return ans; + } +}; +``` \ No newline at end of file