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.
- Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
Example 5:
Input: s = "([)]"
Output: false
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
class Solution:
def isValid(self, s: str) -> bool:
input_stack = ['(', '{', '[']
stack = []
for char in s :
if char in input_stack :
stack.append(char)
else :
if not stack :
return False
curr = stack.pop()
if curr == '(' :
if char != ')' :
return False
elif curr == '{' :
if char != '}' :
return False
else :
if char != ']' :
return False
if stack :
return False
else :
return True
자료구조 - 스택을 공부할 때 가장 먼저 만나게 되는 예제이다. 인풋으로는 열린 괄호들이 포함될 것이고, 닫힌 괄호들이 들어오면서 가장 마지막으로 스택에 들어온 것을 pop 한 후 비교하는 문제이다. 마지막에 스택에 아무것도 남아있지 않다면 True, 그게 아니라면 False를 return 하면 된다
========================= 스터디 후 =========================
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for char in s :
if len(stack) == 0 :
stack.append(char)
continue
if char == ')' and stack[-1] == '(' :
stack.pop()
elif char == '}' and stack[-1] == '{' :
stack.pop()
elif char == ']' and stack[-1] == '[' :
stack.pop()
else :
stack.append(char)
return len(stack) == 0
정답 처리 if stack 라인 이후 저 라인들이 비효율적이고 불필요한 코드 설계라는 의견과 함께, 현업에서 아래로 작성하는 것이 더 나을 것이라 한다. 실제로 위 코드와 아래 코드를 비교하면 조금 더 깔끔하다는 생각이 든다. 우선 이런 문제가 나타나면 if stack 보다는 오류가 잘 일어나지 않는 코드로 설계하는 것이 좋지 않나 생각한다.
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 129. Sum Root to Leaf Numbers (0) | 2025.10.26 |
|---|---|
| [Leetcode/파이썬] 48. Rotate Image (0) | 2025.10.25 |
| [Leetcode/파이썬] 86. Partition List (0) | 2025.10.19 |
| [Leetcode/파이썬] 97. Interleaving String (0) | 2025.10.19 |
| [Leetcode/파이썬] 209. Minimum Size Subarray Sum (1) | 2025.10.11 |