LeetCode 20. Valid Parentheses
๊ดํธ๋ค๋ก ์ด๋ฃจ์ด์ง ๋ฌธ์์ด์ด ์ ํจํ์ง ํ์ธํ๋ ๋ฌธ์ ๋ค.
class Solution:
def isValid(self, s: str) -> bool:
stack = []
parentheses = ['(', '{', '[', ')', '}', ']']
for i in s:
if parentheses.index(i) < 3:
stack.append(parentheses.index(i))
else:
if not stack or stack.pop()+3 != parentheses.index(i):
return False
return False if stack else True
stack
์ ์ถ๊ฐํ๋ค.stack
์ด ๋น์ด์ ธ ์๋ค๋ฉด True, ๊ทธ๋ ์ง ์์ผ๋ฉด Flase.๋ฌธ์ ๋ฅผ ํ๊ณ ๋ค๋ฅธ ํ์ด๋ค์ ๋ณด๋ ๋์
๋๋ฆฌ๋ฅผ ์ด์ฉํด ๊ดํธ๋ค์ ์ง์ง์ ๊ฒฝ์ฐ๊ฐ ๋ง์๋ค.
์ฃผ์ด์ง ์์ด ํด๋น ๋ฌธ์ ์ ๋ฌ๋ฆฌ ๋จ์ํ์ง ์์ ๊ฒฝ์ฐ ์์ ์ฝ๋๊ฐ ์ข์ง ์๊ฒ ๋ค๋ ์๊ฐ์ด ๋ค์ด ์ด๋ฅผ ์ฐธ๊ณ ํด ๊ฐ์ ํด๋ณด์๋ค.
class Solution:
def isValid(self, s: str) -> bool:
stack = []
parentheses = {
'(': ')',
'{': '}',
'[': ']'
}
for i in s:
if i in parentheses:
stack.append(parentheses[i])
else:
if not stack or stack.pop() != i:
return False
return False if stack else True