๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

[leetcode][Easy][Stack] 20. Valid Parentheses ํ’€์ด, ํ•ด์„ค (python)

ttoance 2023. 11. 3. 00:52

 

https://leetcode.com/problems/valid-parentheses/

 

Valid Parentheses - LeetCode

Can you solve this real interview question? Valid Parentheses - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the sam

leetcode.com

 

1์ฐจ ํ’€์ด 

๋‹จ์ˆœํ•œ ์Šคํƒ ๋ฌธ์ œ๋ผ ๊ฐ„๋‹จํžˆ ํ’€์—ˆ์ง€๋งŒ, 

์กฐ๊ฑด์ด ์ถ”๊ฐ€๊ฐ€ ๋˜๋ฉด์„œ ์ข€ ๋ณต์žกํ•œ ํ’€์ด๊ฐ€ ๋˜์—ˆ๋‹ค. 

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        
        stack = []
        for c in s:
            if c in ['(', '{', '[']:
                stack.append(c)
            elif c in [')', '}', ']']:
                # popํ•  ๊ฐ’์ด ์—†๋‹ค๋ฉด 
                if len(stack) == 0:
                    return False 
                
                t = stack.pop()
                if c == ')' and t != '(':
                    return False 
                elif c == '}' and t != '{':
                    return False 
                elif c == ']' and t != '[':
                    return False 
        
        # ๋ชจ๋‘๋‹ค pop ๋˜์–ด์žˆ๋‹ค๋ฉด 
        if len(stack) == 0:
            return True 
        
        return False

 

ํ•ด์„ค

https://www.youtube.com/watch?v=WTzjTskDFMg

ํ•ด์„ค์€ map ํ˜•์‹์„ ์ด์šฉํ•ด์„œ ์กฐ๊ธˆ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€์—ˆ๋‹ค. 

 stack = []
closeToOpen = {")": "(", "]": "[", "}": "{"}
for c in s:
    if c in closeToOpen:
        if stack and stack[-1] == closeToOpen[c]:
            stack.pop()
        else:
            return False
    else:
        stack.append(c)

# ๋น„์–ด์žˆ์œผ๋ฉด true ๋กœ ๋ฆฌํ„ด 
return True if not stack else False

 

๋ฐ˜์‘ํ˜•