763. Partition Labels
https://leetcode.com/problems/partition-labels/
Problem
A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and 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.Note:
Swill have length in range[1, 500].Swill consist of lowercase English letters ('a'to'z') only.
Solution
class Solution {
public:
vector<int> partitionLabels(string S) {
vector<int> partition;
partition.reserve(S.size());
int last_indice[26];
for (int i = 0; i < S.size(); ++i) last_indice[S[i] - 'a'] = i;
int count = 0, max_index = INT_MIN;
for (int i = 0; i < S.size(); ++i) {
if (last_indice[S[i] - 'a'] > max_index) max_index = last_indice[S[i] - 'a'];
++count;
if (max_index == i) {
partition.push_back(count);
count = 0; max_index = INT_MIN;
}
}
return partition;
}
};#string
Last updated
Was this helpful?