[leetcode] 20. Valid Parentheses
2021. 8. 10. 15:56ㆍ노트/Algorithm : 알고리즘
20. Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
class Solution:
def isValid(self, s: str) -> bool:
char_dict = {'(':')', '{':'}','[':']'}
l = []
for st in s:
if st in ['(','{','[']:
l.append(st)
elif st in [')','}',']']:
# l 이 빈 리스트라면
if not l:
return False
# l 꺼냈는데, 괄호 매칭 안된다면
if st != char_dict[l.pop()]:
return False
# 괄호 매칭 됐으면 다음글자 보자
else:
continue
# l에 글자 추가만 되있다면
if len(l) != 0:
return False
return True
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
리스트에서 최솟값 찾기 구현 (0) | 2021.08.11 |
---|---|
[leetcode] 21. Merge Two Sorted Lists (0) | 2021.08.10 |
[leetcode] 14. Longest Common Prefix (0) | 2021.08.10 |
[leetcode] 13. Roman to Integer (0) | 2021.08.06 |
[leetcode] 1. Two Sum (0) | 2021.08.06 |