Skip to content

Commit 04d7767

Browse files
authored
Create partition-labels.cpp
1 parent f3caa79 commit 04d7767

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

C++/partition-labels.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> partitionLabels(string S) {
7+
unordered_map<int, int> lookup;
8+
for (int i = 0; i < S.length(); ++i) {
9+
lookup[S[i]] = i;
10+
}
11+
int first = 0, last = 0;
12+
vector<int> result;
13+
for (int i = 0; i < S.length(); ++i) {
14+
last = max(last, lookup[S[i]]);
15+
if (i == last) {
16+
result.emplace_back(i - first + 1);
17+
first = i + 1;
18+
}
19+
}
20+
return result;
21+
}
22+
};

0 commit comments

Comments
 (0)