728x90
Solved
Easy
Topics
Companies
Hint
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
Constraints:
- 1 <= s.length <= 104
- s consists of parentheses only '()[]{}'.
Accepted
3.8M
Submissions
9.5M
Acceptance Rate
40.2%
나의 풀이
class Solution:
def isValid(self, s: str) -> bool:
list_s = list(s)
# String s를 list화 한다.
answer = True
stack = []
for i in list_s:
# list_s를 돌면서
if i == '(' or i =='[' or i =='{':
# i가 '('거나 '['거나 '{'라면
stack.append(i)
# stack에 전부 append한다.
elif len(stack) != 0:
# stack에 요소가 남아 있을 때
if (i == ']' and stack[-1] == '[') or (i == ')' and stack[-1] == '(') or (i == '}' and stack[-1] == '{'):
# 위의 조건을 만족한다면
stack.pop()
# stack에서 pop해준다.
else :
# stack에 남아 있는 요소가 없다면
answer = False
# answer는 False다.
break
# 반복문 탈출
else :
# if i == '(' or i =='[' or i =='{'의 조건을 만족하지 않는다면
answer = False
# answer는 False다.
break
# 반복문 탈출
if len(stack) != 0:
# 만약 반복문을 전부 돌고 나서도 stack에 요소가 남아 있다면
answer = False
# answer는 False가 된다.
return answer
728x90
'Coding Test' 카테고리의 다른 글
[CT] 프로그래머스 접미사인지 확인하기 Python3 ver. (0) | 2023.11.01 |
---|---|
[CT] 프로그래머스 최소직사각형 Python3 ver. (0) | 2023.10.21 |
[CT] LEET CODE 14. Longest Common Prefix (0) | 2023.09.26 |
[CT] 프로그래머스 마지막 두 원소 Python3 ver. (0) | 2023.09.23 |
[CT] Leet Code 287. Find the Duplicate Number (0) | 2023.09.19 |