1544. Make The String Great #283
-
Topics: Given a string A good string is a string which doesn't have two adjacent characters
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good. Return the string after making it good. The answer is guaranteed to be unique under the given constraints. Notice that an empty string is also good. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem asks us to make a given string "good" by removing adjacent characters that form a "bad pair." A "bad pair" is defined as two adjacent characters where one is the uppercase version of the other (or vice versa). The goal is to repeatedly remove these bad pairs until no more exist in the string. Key Points:
Approach:
Plan:
Let's implement this solution in PHP: 1544. Make The String Great <?php
/**
* @param String $s
* @return String
*/
function makeGood(string $s): string
{
$ans = [];
foreach(str_split($s) as $c) {
if (!empty($ans) && $this->isBadPair(end($ans), $c)) {
array_pop($ans);
} else {
$ans[] = $c;
}
}
return implode('', $ans);
}
/**
* @param $a
* @param $b
* @return bool
*/
private function isBadPair($a, $b): bool
{
return $a != $b && strtolower($a) == strtolower($b);
}
// Example usage:
$s1 = "leEeetcode";
$s2 = "abBAcC";
$s3 = "s";
echo makeGood($s1) . "\n"; // Output: "leetcode"
echo makeGood($s2) . "\n"; // Output: ""
echo makeGood($s3) . "\n"; // Output: "s"
?> Explanation:
Example Walkthrough:Example 1:Input:
Final output: Example 2:Input:
Final output: Example 3:Input:
Final output: Time Complexity:
Output for Examples:
This problem can be efficiently solved using a stack-based approach. The stack ensures that we can check and remove bad pairs in O(1) time, making the overall solution run in linear time. By applying the above approach, we ensure that the string becomes "good" after processing all characters, providing the correct output for all given cases. |
Beta Was this translation helpful? Give feedback.
The problem asks us to make a given string "good" by removing adjacent characters that form a "bad pair." A "bad pair" is defined as two adjacent characters where one is the uppercase version of the other (or vice versa). The goal is to repeatedly remove these bad pairs until no more exist in the string.
Key Points:
Approach:
Stack-b…