[LeetCode] Make The String Great

1544. Make The String Great

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] and s[i + 1] where:

  • 0 <= i <= s.length - 2
  • 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 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string makeGood(string s) {
string st = "";
for(auto ch : s) {
if(st.empty()) st.push_back(ch);
else if(islower(ch) and st.back() == toupper(ch)) st.pop_back();
else if(isupper(ch) and st.back() == tolower(ch)) st.pop_back();
else st.push_back(ch);
}
return st;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/08/PS/LeetCode/make-the-string-great/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.