LeetCode Solutions
763. Partition Labels
Time: $O(n)$ Space: $O(128) = O(1)$
class Solution {
public:
vector<int> partitionLabels(string S) {
vector<int> ans;
vector<int> rightmost(128);
for (int i = 0; i < S.length(); ++i)
rightmost[S[i]] = i;
int l = 0; // First index of current running string
int r = 0; // Right most so far
for (int i = 0; i < S.length(); ++i) {
r = max(r, rightmost[S[i]]);
if (r == i) {
ans.push_back(i - l + 1);
l = i + 1;
}
}
return ans;
}
};
class Solution {
public List<Integer> partitionLabels(String S) {
List<Integer> ans = new ArrayList<>();
int[] rightmost = new int[128];
for (int i = 0; i < S.length(); ++i)
rightmost[S.charAt(i)] = i;
int l = 0; // First index of current running string
int r = 0; // Right most so far
for (int i = 0; i < S.length(); ++i) {
r = Math.max(r, rightmost[S.charAt(i)]);
if (r == i) {
ans.add(i - l + 1);
l = i + 1;
}
}
return ans;
}
}
class Solution:
def partitionLabels(self, S: str) -> List[int]:
ans = []
letterToRightmostIndex = {c: i for i, c in enumerate(S)}
l = 0
r = 0
for i, c in enumerate(S):
r = max(r, letterToRightmostIndex[c])
if i == r:
ans.append(r - l + 1)
l = r + 1
return ans