| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- ProblemSoving
- C++
- Kubernetes
- 3D PRINTING
- Count Monobit Integers
- ProblemSolving
- GitLab
- swift
- 하늘과 바람과 별과 시
- Code Jam
- leetcode
- MySQL
- Code Jam 2022
- hackerrank
- 리트코드
- Python
- Qualification Round
- 코딩테스트
- LEVEL 2
- First Unique Character in a String
- K8S
- 문제해결
- 파이썬
- 2022
- 알고리즘
- 해커랭크
- 하늘과 바람과 별과 詩
- 프로그래머스
- Algorithm
Archives
- Today
- Total
공대생의 비망록
[LeetCode][Easy] Valid Parentheses 문제 Python 풀이 본문
Programming Language/Python
[LeetCode][Easy] Valid Parentheses 문제 Python 풀이
myungsup1250 2026. 2. 10. 15:24자료구조를 공부하게 되면 Stack의 특성을 활용하도록 꼭 한번은 경험하게 되는 문제를 LeetCode 플랫폼에서도 풀게 되었다.
기존에는 C나 C++, Java로 구현했었는데 이번에는 Python으로 여러 방법을 구현해보았다.
if-else 구문을 떡칠해서 문제를 해결하는 가장 기본적인 (멍청한) 방식:
class Solution:
def isValid(self, s: str) -> bool:
stack = list()
for ch in s:
if ch == '(' or ch == '{' or ch == '[':
stack.append(ch)
elif ch == ')':
if len(stack) > 0 and stack[-1] == '(':
stack.pop()
else:
return False
elif ch == '}':
if len(stack) > 0 and stack[-1] == '{':
stack.pop()
else:
return False
elif ch == ']':
if len(stack) > 0 and stack[-1] == '[':
stack.pop()
else:
return False
# else: # ch is not '(', ')', '{', '}', '[', ']'
# continue
if len(stack) == 0:
return True
return False
Dictionary 자료구조를 활용해서 괄호 유형 별로 쌍을 이루어 보다 간결한 로직으로 문제를 해결하는 방법:
class Solution:
def isValid(self, s: str) -> bool:
mydict = {')':'(', '}':'{', ']':'['}
stack = list()
for ch in s:
if ch in mydict.values(): # '(', '{', '['
stack.append(ch)
elif ch in mydict.keys(): # ')', '}', ']'
if len(stack) > 0 and stack[-1] == mydict[ch]:
stack.pop()
else:
return False
if len(stack) == 0:
return True
return False
Dictionary 자료구조 활용 방식을 보다 개선하고 코드를 보다 Pythonic하게 수정한 방법:
class Solution:
def isValid(self, s: str) -> bool:
mydict = {'(':')', '{':'}', '[':']'}
stack = list()
for ch in s:
if ch in mydict.keys(): # '(', '{', '['
stack.append(mydict[ch])
elif ch in mydict.values(): # ')', '}', ']'
if len(stack) > 0 and stack[-1] == ch:
stack.pop()
else:
return False
return len(stack) == 0'Programming Language > Python' 카테고리의 다른 글
| [LeetCode][Easy] Longest Common Prefix 문제 Python 풀이 (0) | 2026.02.09 |
|---|---|
| [LeetCode][Easy] Valid Palindrome 문제 Python 풀이 (0) | 2026.02.09 |
| [LeetCode][Easy] First Unique Character in a String 문제 Python 풀이 (0) | 2026.02.09 |
| [LeetCode][Easy] Valid Anagram 문제 Python 풀이 (0) | 2026.02.08 |
| [LeetCode][Easy] Count Monobit Integers 문제 Python 풀이 (0) | 2026.02.08 |
Comments
