LeetCode 1544 solution

LeetCode  1544 solution

problem

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.

Example 1

  • Input: s = "leEeetcode"
  • Output: "leetcode"
  • Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".

python

class Solution:
    def makeGood(self, s: str) -> str:
        stack = []
        for i in range(len(s)):
            if not stack:
                stack.append(s[i])
                continue
            elif s[i].lower() == stack[-1].lower() and s[i] != stack[-1]:
                stack.pop()
            else:
                stack.append(s[i])
        return "".join(stack)

이것 역시 엄청나게 어려운 stack 문제라고 볼 수는 없다. 다만 elif s[i].lower() == stack[-1].lower() and s[i] != stack[-1]: 이 부분에 대해서 생각하지 못하면 효율적으로 코드를 짤 수 없을지도 모른다. 모두 lower로 수렴하기 때문에 조건도 lower에 대한 확인을 해주면 된다. stack[-1] != s[i]를 함께 살펴보고 있기 때문에, 같이 lowercase인 경우라도 해당 조건과 함께라면 둘 중 하나는 uppercase인 경우에 대한 검색이란 것을 알 수 있다.