물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

1047. Remove All Adjacent Duplicates In String

BEstyle 2023. 3. 23. 14:10

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

 

Example 1:

Input: s = "abbaca"
Output: "ca"
Explanation: 
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Example 2:

Input: s = "azxxzy"
Output: "ay"

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.

#https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

'''
1. 아이디어 :
    스택을 이용하여 풀 수 있다.
2. 시간복잡도 :
    O(n)
3. 자료구조 :
    스택
'''


class Solution:
    def removeDuplicates(self, s: str) -> str:
        if not s:
            return ""
        alpha=[s[0]]
        for alp in s[1:]:
            if not alpha or alpha[-1]!=alp:
                alpha.append(alp)
            elif alpha[-1]==alp:
                alpha.pop()

        return "".join(alpha)

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

2235. Add Two Integers  (0) 2023.03.23
231. Power of Two  (0) 2023.03.23
697. Degree of an Array  (0) 2023.03.23
290. Word Pattern  (0) 2023.03.23
1200. Minimum Absolute Difference  (0) 2023.03.23