Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) % 2 != 0:
return False
elif len(s) == 0:
return False
stack = []
parameters = {")": "(", "}": "{", "]": "["}
for string in s:
if string in parameters:
if stack:
stack_pop = stack.pop()
if parameters[string] != stack_pop:
return False
else:
stack.append(string)
return True
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
lookup = {")": "(", "}": "{", "]": "["}
for p in s:
if p in lookup.values():
stack.append(p)
elif stack and lookup[p] == stack[-1]:
stack.pop()
else:
return False
return stack == []
코드 출처 ㅣ Timothy Chang의 영상
반성하자. 딕셔너리를 쓰고 왜 활용을 안하니...