Published:
Updated:

  • Reference
  • ์นด์นด์˜ค ๊ธฐ์ถœ ๋ฌธ์ œ๋„ ๊ทธ๋ ‡๊ณ  ์ด๋Ÿฐ ๋ฌธ์ œ๋“ค์€ ์‹น๋‹ค stack์„ ์‚ฌ์šฉํ•ด์•ผ ํ’€๋ฆฌ๋Š” ๋ฌธ์ œ
  • and ์—ฐ์‚ฐ์€ ๊ตณ์ด ์กฐ๊ฑด ๋ชจ๋‘๋ฅผ ๋น„๊ตํ•˜์ง€ ์•Š์Œ
    • False๊ฐ€ ๋‚˜์˜ค๋ฉด ์ฆ‰์‹œ ๋น„๊ต๋ฅผ ์ค‘๋‹จํ•จ


Solution

import collections


class Solution:
    def isValid(self, s: str) -> bool:
        # parentheses_map = collections.defaultdict(str)
        # parentheses_map['('] = ')'
        # parentheses_map['{'] = '}'
        # parentheses_map['['] = ']'

        # i = 0
        # while i < len(s) - 1:
        #     if parentheses_map[s[i]] == s[i + 1]:
        #         i += 2
        #         continue
        #
        #     return False
        #
        # return True
        # ์œ„์ฒ˜๋Ÿผํ•˜๋ฉด "{[]}"์™€ ๊ฐ™์€ ์ผ€์ด์Šค์—์„œ ๊ฑธ๋Ÿฌ์ง -> ์ฆ‰ ์Šคํƒ ์จ์•ผ ํ•˜๋Š” ๋ฌธ์ œ

        parentheses_map = collections.defaultdict(str)
        parentheses_map[')'] = '('
        parentheses_map['}'] = '{'
        parentheses_map[']'] = '['

        stack = []
        for each in s:
            if stack and parentheses_map[each] == stack[-1]:
                    stack.pop()
                    continue

            stack.append(each)

        if stack:
            return False

        return True

Leave a comment