17. Partition Labels
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.
Solution:
Approach:
We keep track of max last occurrence of a new character from start. When we reach the end of occurrence of all characters we push and increase start
class Solution
{
public:
vector<int> partitionLabels(string s)
{
vector<int> res;
vector<int> v(26, 0);
for (int i = 0; i < s.length(); i++)
{
v[s[i] - 97] = i;
}
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++)
{
end = max(end, v[s[i] - 97]);
if (end == i)
{
int x = (end - start) + 1;
res.push_back(x);
start = i + 1;
end = i + 1;
}
}
return res;
}
};
Time Complexity: O(n)
Last updated
Was this helpful?