Skip to content

1544. Make The String Great 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  string makeGood(string s) {
    string ans;
    for (const char c : s)
      if (!ans.empty() && isBadPair(ans.back(), c))
        ans.pop_back();
      else
        ans.push_back(c);
    return ans;
  }

  bool isBadPair(char a, char b) {
    return a != b && tolower(a) == tolower(b);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public String makeGood(String s) {
    StringBuilder sb = new StringBuilder();
    for (char c : s.toCharArray())
      if (sb.length() > 0 && isBadPair(sb.charAt(sb.length() - 1), c))
        sb.deleteCharAt(sb.length() - 1);
      else
        sb.append(c);
    return sb.toString();
  }

  private boolean isBadPair(char a, char b) {
    return a != b && Character.toLowerCase(a) == Character.toLowerCase(b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def makeGood(self, s: str) -> str:
    ans = []
    for c in s:
      if ans and self._is_bad_pair(ans[-1], c):
        ans.pop()
      else:
        ans.append(c)
    return ''.join(ans)

  def _is_bad_pair(self, a: str, b: str) -> bool:
    return a != b and a.lower() == b.lower()