763. Partition Labels #1497
-
Topics: You are given a string Note that the partition is done so that after concatenating all the parts in order, the resultant string should be Return a list of integers representing the size of these parts. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to partition a string into as many parts as possible such that each character appears in at most one part. The goal is to return the sizes of these parts in a list. ApproachThe key insight to solve this problem efficiently is to use a greedy algorithm combined with a hash map to track the last occurrence of each character. Here's the step-by-step approach:
Let's implement this solution in PHP: 763. Partition Labels <?php
/**
* @param String $s
* @return Integer[]
*/
function partitionLabels($s) {
$last = array();
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$char = $s[$i];
$last[$char] = $i;
}
$result = array();
$start = 0;
$end = 0;
for ($i = 0; $i < $n; $i++) {
$char = $s[$i];
$end = max($end, $last[$char]);
if ($i == $end) {
array_push($result, $end - $start + 1);
$start = $end + 1;
}
}
return $result;
}
// Test cases
$s1 = "ababcbacadefegdehijhklij";
print_r(partitionLabels($s1)); // Output: [9,7,8]
$s2 = "eccbbbbdec";
print_r(partitionLabels($s2)); // Output: [10]
?> Explanation:
This approach ensures that each partition is as small as possible while including all necessary characters, thus maximizing the number of partitions. The algorithm efficiently processes the string in linear time, making it both optimal and easy to understand. |
Beta Was this translation helpful? Give feedback.
We need to partition a string into as many parts as possible such that each character appears in at most one part. The goal is to return the sizes of these parts in a list.
Approach
The key insight to solve this problem efficiently is to use a greedy algorithm combined with a hash map to track the last occurrence of each character. Here's the step-by-step approach:
Track Last Occurrences: First, we create a hash map to record the last index at which each character appears in the string. This helps us determine the furthest point we need to extend a partition to include all occurrences of a character.
Iterate and Expand Partitions: Using two pointers, we iterate through the string. The…