-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
1544. Make The String Great #284
Comments
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. |
Discussed in #283
Originally posted by mah-shamim August 9, 2024
Topics:
String
,Stack
Given a string
s
of lower and upper case English letters.A good string is a string which doesn't have two adjacent characters
s[i]
ands[i + 1]
where:0 <= i <= s.length - 2
s[i]
is a lower-case letter ands[i + 1]
is the same letter but in upper-case or vice-versa.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:
s = "leEeetcode"
"leetcode"
In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Example 2:
"abBAcC"
""
Example 3:
s = "s"
"s"
Constraints:
1 <= s.length <= 100
s
contains only lower and upper case English letters.Hint:
The text was updated successfully, but these errors were encountered: