복's

[ LeetCode - 20 ] Valid Parentheses 본문

알고리즘/LeetCode

[ LeetCode - 20 ] Valid Parentheses

나복이 2023. 10. 30. 04:52
728x90

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

 

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) 괄호를 stack에 집어 넣는다.

2) 넣을 괄호가 닫는 괄호 ')', ']', '}' 라면 stack의 top을 확인해서 짝이 맞다면 pop(del) 해준다.

3) return시 stack이 비어있다면 유효한 괄호라고 볼 수 있다.


[ 📌 코드 - Python ]

조건이 길긴 하지만  결과가 좋으니 손보지 않아도 될 것 같다. (짧은 코드 찾으러 다니지 않아도 될듯)

class Solution:
    def isValid(self, s: str) -> bool:
        result = []

        for word in s:
            if len(result) != 0:
                if (word == ")" and result[-1] == "(") or (word == "]" and result[-1] == "[") or (word == "}" and result[-1] == "{"):
                    del result[-1]
                    continue
            
            result.append(word)

        return len(result) == 0

[ 📌 결과 ]

[ Result ]

728x90