Skip to content

Commit aa6d6a9

Browse files
committed
[7th batch] week 6 - valid parentheses
1 parent 1686e63 commit aa6d6a9

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

โ€Žvalid-parentheses/liza0525.pyโ€Ž

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,37 @@ def isValid(self, s: str) -> bool:
6161
if stack:
6262
return False
6363
return True
64+
65+
66+
67+
# 7๊ธฐ ํ’€์ด
68+
# ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
69+
# - s์˜ ๊ธธ์ด n์— ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์ •ํ•ด์ง
70+
# ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
71+
# - ์™ผ์ชฝ ๊ด„ํ˜ธ๋ฅผ ์ €์žฅํ•  stacks(list) ๋ณ€์ˆ˜์˜ ๊ธธ์ด๋Š” s์˜ ๊ธธ์ด์— ์˜ํ•ด ์ •ํ•ด์ง
72+
# - stack์˜ ์ตœ๋Œ€ ๊ธธ์ด๋Š” s๊ฐ€ ๋ชจ๋‘ ์™ผ์ชฝ ๊ด„ํ˜ธ๋กœ ๋˜์–ด ์žˆ์„ ๋•Œ
73+
class Solution:
74+
def isValid(self, s: str) -> bool:
75+
# ์˜ค๋ฅธ์ชฝ ๊ด„ํ˜ธ๊ฐ€ ๋“ค์–ด์˜ฌ ๋•Œ์˜ ์Œ์„ ์‰ฝ๊ฒŒ ์ฐพ๊ธฐ ์œ„ํ•ด ๋งŒ๋“  dictionary
76+
brackets = {")": "(", "}": "{", "]": "["}
77+
78+
# ์™ผ์ชฝ ๊ด„ํ˜ธ๋ฅผ ์ €์žฅํ•  list
79+
stacks = []
80+
81+
for ss in s:
82+
if stacks and ss in brackets.keys():
83+
# stacks์— ๊ด„ํ˜ธ๊ฐ€ ์ €์žฅ๋˜์–ด ์žˆ์œผ๋ฉด์„œ, ss๋กœ ์˜ค๋ฅธ์ชฝ ๊ด„ํ˜ธ๊ฐ€ ๋“ค์–ด์˜ค๋ฉด
84+
# ์Œ์„ ๋น„๊ต
85+
if stacks[-1] != brackets[ss]:
86+
# stacks์˜ ๋งˆ์ง€๋ง‰ ๋ฌธ์ž(๊ฐ€์žฅ ๋Šฆ๊ฒŒ ๋“ค์–ด์˜จ ์™ผ์ชฝ ๊ด„ํ˜ธ)์™€ ํ˜„์žฌ ๋“ค์–ด์˜จ ์˜ค๋ฅธ์ชฝ ๊ด„ํ˜ธ์˜ ์Œ์ด ๊ฐ™์ง€ ์•Š์œผ๋ฉด
87+
# ๊ด„ํ˜ธ์˜ ์Œ์ด ๋งž์ง€ ์•Š์œผ๋ฏ€๋กœ False๋ฅผ early return
88+
return False
89+
else:
90+
# ์Œ์ด ๋งž๋Š”๋‹ค๋ฉด stacks์— ์žˆ๋Š” ๋งˆ์ง€๋ง‰ ์™ผ์ชฝ ๊ด„ํ˜ธ๋Š” ๋”์ด์ƒ ๋น„๊ตํ•  ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ pop
91+
stacks.pop()
92+
else:
93+
# ss๊ฐ€ ์™ผ์ชฝ ๊ด„ํ˜ธ์ธ ๊ฒฝ์šฐ์—” stacks์— ์Œ“์•„์ค€๋‹ค
94+
stacks.append(ss)
95+
96+
# ๋ชจ๋“  ์Œ๋น„๊ต๋ฅผ ํ•˜๊ณ  stacks์— ๊ด„ํ˜ธ๊ฐ€ ๋‚จ์•„์žˆ๋Š” ์ง€ ์—ฌ๋ถ€๋ฅผ return
97+
return not stacks

0 commit comments

Comments
ย (0)