[Programmers] Level 2. 짝지어 제거하기

Seo Seung Woo·2022년 7월 25일
0
post-thumbnail

Level 2. 짝지어 제거하기


❔Thinking

  • 문자열이 2번 반복된 경우 삭제한다.
  • 삭제한 문자열을 합치고, 다시 중복된 문자열이 있는지 확인한다.
  • 모든 문자열이 삭제 가능하면 1, 그 외에는 0을 반환한다.

💻Solution

  1. Brute Force

      def solution(s):
          dubbled_s = [char+char for char in set(s)]
          check_flag = True
          while check_flag is True:
              check_flag = False
              for dub_s in dubbled_s:
                  if dub_s in s:
                      s = s.replace(dub_s, '')
                      check_flag = True
          return 1 if len(s) == 0 else 0
  2. Stack

      def solution(s):
          s_stack = [s[0]]
          for char in s[1:]:
              if len(s_stack) >= 1 and s_stack[-1] == char:
                  s_stack.pop()
              else:
                  s_stack.append(char)
    
          return 1 if len(s_stack) == 0 else 0

🗝️keypoint

  • 문자열에서는 pop()을 사용할 수 없다.
  • stack 문제에서는 반드시 list out of range를 주의한다.
profile
Code for people

0개의 댓글