Leetcode 1544. Make The String Great
Given a string s
of lower and upper case English letters.
A string is considered “great” if there are no two adjacent characters s[i]
and s[i + 1]
where:
s[i]
is a lower-case letter and s[i + 1]
is the same letter but in upper-case or vice versa.To make the string great, you can choose two adjacent characters that make the string not great and remove them.
Repeat this process until you make the string great.
Return the resulting string. It is guaranteed that the answer is unique under the given constraints.
Example 1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, remove "eE", then "leEeetcode" becomes "leetcode".
Example 2:
Input: s = "abBAcC"
Output: ""
Explanation: Remove "abBA", then the string becomes "cC", then remove "cC", so the final string is empty.
Example 3:
Input: s = "s"
Output: "s"
s
?
s
can be up to 100
.We can use a stack to process the string. The idea is to traverse the string character by character and use the stack to keep track of the characters we’ve seen.
s
.public class Solution {
public String makeGood(String s) {
StringBuilder stack = new StringBuilder();
for (char ch : s.toCharArray()) {
int size = stack.length();
if (size > 0 &&
Math.abs(stack.charAt(size - 1) - ch) == 32) {
stack.deleteCharAt(size - 1);
} else {
stack.append(ch);
}
}
return stack.toString();
}
}
The time complexity of this solution is O(n)
, where n
is the length of the string s
. This is because we are processing each character of the string exactly once.
The space complexity is also O(n)
in the worst case if no characters are removed, and all characters are stored in the stack.
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?