Notice
Recent Posts
Recent Comments
Link
복's
[ LeetCode - 20 ] Valid Parentheses 본문
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
[ 📌 결과 ]
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[ LeetCode - 22 ] Generate Parentheses (1) | 2023.10.30 |
---|---|
[ LeetCode - 42 ] Trapping Rain Water (1) | 2023.10.30 |
[ LeetCode - 282 ] Expression Add Operators (0) | 2023.10.30 |
[ LeetCode - 14 ] Longest Common Prefix (1) | 2023.10.29 |
[ LeetCode - 412 ] Fizz Buzz (0) | 2023.10.29 |