Skip to content

Commit

Permalink
feat: Add Valid Parentheses solution
Browse files Browse the repository at this point in the history
  • Loading branch information
thispath98 committed Jan 13, 2025
1 parent 905a15a commit a33faa0
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions valid-parentheses/thispath98.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution:
def isValid(self, s: str) -> bool:
"""
Intuition:
stack ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋‹ซํžˆ๋Š” ๊ด„ํ˜ธ๊ฐ€ ์˜ฌ ๊ฒฝ์šฐ
stack์˜ ๋งˆ์ง€๋ง‰๊ณผ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.
Time Complexity:
O(N):
๋ฌธ์ž์—ด์„ ํ•œ๋ฒˆ ์Šค์บ”ํ•˜๋ฉด์„œ ์กฐ๊ฑด๋ฌธ์„ ํ™•์ธํ•˜๋ฏ€๋กœ
O(N)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์†Œ์š”๋œ๋‹ค.
Space Complexity:
O(N):
์ตœ์•…์˜ ๊ฒฝ์šฐ ๋ฌธ์ž์—ด ๊ฐœ์ˆ˜๋งŒํผ stack์— ์ €์žฅํ•œ๋‹ค.
"""
stack = []
for ch in s:
if ch in ["(", "{", "["]:
stack.append(ch)
elif ch in [")", "}", "]"]:
if stack and (
(ch == ")" and stack[-1] == "(")
or (ch == "}" and stack[-1] == "{")
or (ch == "]" and stack[-1] == "[")
):
stack.pop()
else:
return False

if stack:
return False
else:
return True

0 comments on commit a33faa0

Please sign in to comment.