파비의 매일매일 공부기록

2023.04.10 Today's Challenge 본문

Problem Solving/LeetCode

2023.04.10 Today's Challenge

fabichoi 2023. 4. 10. 23:45

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

전형적인 스택을 활용하면 되는 문제

class Solution:
    def isValid(self, s: str) -> bool:
        st = []
        
        for c in s:
            if c == '(' or c == '{' or c == '[':
                st.append(c)
            else:
                if not st:
                    return False
                    
                if c == ')' and st[-1] == '(':
                    st.pop()
                elif c == '}' and st[-1] == '{':
                    st.pop()
                elif c == ']' and st[-1] == '[':
                    st.pop()
                else:
                    return False
        
        return not st
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.04.12 Today's Challenge  (0) 2023.04.12
2023.04.11 Today's Challenge  (0) 2023.04.11
2023.04.09 Today's Challenge  (0) 2023.04.09
2023.04.08 Today's Challenge  (0) 2023.04.08
2023.04.07 Today's Challenge  (0) 2023.04.07
Comments