3170. Lexicographically Minimum String After Removing Stars #1778
-
Topics: You are given a string While there is a
Return the lexicographically smallest1 resulting string after removing all Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to remove all '' characters from the string while ensuring that each '' is removed along with the smallest non-'*' character to its left. If there are multiple smallest characters, we remove the rightmost one to ensure the resulting string is lexicographically smallest. Approach
Let's implement this solution in PHP: 3170. Lexicographically Minimum String After Removing Stars <?php
/**
* @param String $s
* @return String
*/
function clearStars($s) {
$s = str_split($s);
$buckets = array_fill(0, 26, []);
$n = count($s);
for ($i = 0; $i < $n; $i++) {
if ($s[$i] == '*') {
for ($j = 0; $j < 26; $j++) {
if (!empty($buckets[$j])) {
$index = array_pop($buckets[$j]);
$s[$index] = '';
$s[$i] = '';
break;
}
}
} else {
$idx = ord($s[$i]) - ord('a');
$buckets[$idx][] = $i;
}
}
return implode('', $s);
}
// Test cases
echo clearStars("aaba*") . "\n"; // Output: aab
echo clearStars("abc") . "\n"; // Output: abc
echo clearStars("abc*def*g*") . "\n"; // Output: abdf
?> Explanation:
This approach efficiently processes each character and ensures the lexicographically smallest result by always removing the rightmost smallest character for each '*', leveraging bucket sorting for constant-time access to the smallest character. The solution handles large inputs within optimal time complexity. |
Beta Was this translation helpful? Give feedback.
We need to remove all '' characters from the string while ensuring that each '' is removed along with the smallest non-'*' character to its left. If there are multiple smallest characters, we remove the rightmost one to ensure the resulting string is lexicographically smallest.
Approach
Problem Analysis: The problem requires processing each '' in the string by removing it along with the smallest character to its left. The key challenge is efficiently finding the smallest character to the left of each '' and ensuring the solution is optimal for large input sizes (up to 10^5 characters).
Intuition: The lexicographically smallest string is achieved by preserving as many leftmost characte…