vault backup: 2022-09-06 16:27:17
This commit is contained in:
parent
52bc1310ca
commit
0a3691373f
|
@ -16,7 +16,7 @@
|
||||||
>
|
>
|
||||||
> ##### Additional tags:
|
> ##### Additional tags:
|
||||||
>
|
>
|
||||||
> #leetcode
|
> #leetcode #CS_list_need_practicing
|
||||||
>
|
>
|
||||||
> ##### Revisions:
|
> ##### Revisions:
|
||||||
>
|
>
|
||||||
|
@ -57,6 +57,70 @@ A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits
|
||||||
### Thoughts
|
### Thoughts
|
||||||
|
|
||||||
> [!summary]
|
> [!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
|
### Solution
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
vector<int> 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<int> last(26);
|
||||||
|
|
||||||
|
int segEnd = 0, segStart = 0;
|
||||||
|
|
||||||
|
vector<int> 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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in a new issue