def solution(s):
stack = [] # 스택 초기화
for ch in s: # 문자열 s를 한 글자씩 반복해서 읽음
if ch in ['(', '[', '{']: # 여는 괄호라면 스택에 추가
stack.append(ch)
else: # 닫는 괄호인 경우
if(len(stack)==0): # 닫는 괄호만 남아 있어서!! stack이 비어서 올바르지 않은 괄호 문자열인 경우,
return False
if ch == ')' and stack[-1] == '(': # 괄호 쌍이 맞는 경우 스택에서 제거(pop)
stack.pop()
elif ch == ']' and stack[-1] == '[':
stack.pop()
elif ch == '}' and stack[-1] == '{':
stack.pop()
else: # 괄호 쌍이 맞지 않는 경우, 올바르지 않은 괄호 문자열인 경우 #s = "({[)]}"
return False
return not stack # 문자열을 모두 읽은 후 스택에 남은 괄호가 없어서 올바른 괄호 문자열인 경우
# s="()))" #반례1 닫는 괄호만 남아 있는 경우
# s = "({[)]}" #괄호의 쌍이 맞지 않는 경우
s = "((()))[()]" #for문을 다 순회하고 stack에 비어있는 경우
print(solution(s))
https://leetcode.com/problems/valid-parentheses/
Valid Parentheses - LeetCode
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 same type of brackets. 2. Open brackets must be
leetcode.com
'개발남노씨(Coding Test)' 카테고리의 다른 글
HashTable - Two Sum (과거인덱스, 지금인덱스) (0) | 2023.02.16 |
---|---|
Daily Temperatures - stack문제 (0) | 2023.02.16 |
Linked List 3 - Brower History (0) | 2023.02.15 |
Linked List 2 - tail 추가 (0) | 2023.02.15 |
Linked List 1 (0) | 2023.02.03 |