Leetcode 763. Partition Labels
You are given a string s
. 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.
s
guaranteed to be non-empty and consist only of lowercase English letters?Let’s assume:
s
is non-empty and contains only lowercase English letters.To solve this problem, we can use the following approach:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
vector<int> partitionLabels(string s) {
// Step 1: Record the last occurrence of each character.
unordered_map<char, int> last_occurrence;
for (int i = 0; i < s.size(); ++i) {
last_occurrence[s[i]] = i;
}
// Step 2: Initialize variables to track partitions.
int start = 0, end = 0;
vector<int> partitions;
// Step 3: Iterate through the string to find partitions.
for (int i = 0; i < s.size(); ++i) {
end = max(end, last_occurrence[s[i]]);
if (i == end) {
partitions.push_back(end - start + 1);
start = i + 1;
}
}
return partitions;
}
// Example usage:
int main() {
string s = "ababcbacadefegdehijhklij";
vector<int> partitionSizes = partitionLabels(s);
for (int size : partitionSizes) {
cout << size << " ";
}
cout << endl;
return 0;
}
start
and end
, to keep track of the current partition boundaries.end
whenever we encounter a character whose last occurrence is further to the right. When the current index i
matches the end
, it means we have completed a partition and we can record its size.s
. We traverse the string twice—once to record the last occurrences and once to construct the partitions.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?