Skip to content

Commit

Permalink
Create partition-labels.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Jan 14, 2018
1 parent ffe6325 commit 2e1f778
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions C++/partition-labels.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Time: O(n)
// Space: O(n)

class Solution {
public:
vector<int> partitionLabels(string S) {
unordered_map<int, int> lookup;
for (int i = 0; i < S.length(); ++i) {
lookup[S[i]] = i;
}
int first = 0, last = 0;
vector<int> result;
for (int i = 0; i < S.length(); ++i) {
last = max(last, lookup[S[i]]);
if (i == last) {
result.emplace_back(i - first + 1);
first = i + 1;
}
}
return result;
}
};

0 comments on commit 2e1f778

Please sign in to comment.