-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy path763.partition-labels.cpp
More file actions
55 lines (52 loc) · 1.49 KB
/
763.partition-labels.cpp
File metadata and controls
55 lines (52 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Tag: Greedy, Hash Table, Two Pointers, String
// Time: O(N)
// Space: O(N)
// Ref: -
// Note: -
// Video: https://youtu.be/kRfwsXnuCz0
// You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
// Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
// Return a list of integers representing the size of these parts.
//
// Example 1:
//
// Input: s = "ababcbacadefegdehijhklij"
// Output: [9,7,8]
// Explanation:
// The partition is "ababcbaca", "defegde", "hijhklij".
// This is a partition so that each letter appears in at most one part.
// A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
//
// Example 2:
//
// Input: s = "eccbbbbdec"
// Output: [10]
//
//
// Constraints:
//
// 1 <= s.length <= 500
// s consists of lowercase English letters.
//
//
class Solution {
public:
vector<int> partitionLabels(string s) {
int n = s.size();
unordered_map<char, int> indexes;
for (int i = 0; i < n; i++) {
indexes[s[i]] = i;
}
int i = 0;
vector<int> res;
int right = 0;
for (int j = 0; j < n; j++) {
right = max(right, indexes[s[j]]);
if (j == right) {
res.push_back(j - i + 1);
i = j + 1;
}
}
return res;
}
};