Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
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
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
Hint
Recall
(推推)編譯器 Compiler 的 課堂實作有用上。
思路 便 Start Coding
if 欲放進的 括弧 在 stack 的最上面 則移除
else 加進 stack
最後全部括弧走一遍後
如果 stack 為 空 則 return True
否則 return False
正解 即 思路
class Solution:
def isValid(self, s: str) -> bool:
stack = []
map_pair = {}
map_pair['('] = ''
map_pair[')'] = '('
map_pair['['] = ''
map_pair[']'] = '['
map_pair['{'] = ''
map_pair['}'] = '{'
for i in range(len(s)):
if len(stack)!=0 and map_pair[s[i]] == stack[len(stack)-1]:
stack.pop()
else:
stack.append(s[i])
if len(stack)==0:
return True
else:
return False
Result