LeetCode--20.有效的括號
阿新 • • 發佈:2018-11-25
有效的括號
LeetCode-->20.有效的括號
給定一個只包括 '(',')','{','}','[',']' 的字串,判斷字串是否有效。
有效字串需滿足:
- 左括號必須用相同型別的右括號閉合。
- 左括號必須以正確的順序閉合。
- 注意空字串可被認為是有效字串。
示例 1:
輸入: "()"
輸出: true
示例 2:
輸入: "()[]{}"
輸出: true
示例 3:
輸入: "(]"
輸出: false
示例 4:
輸入: "([)]"
輸出: fals
示例 5:
輸入: "{[]}"
輸出: true
解答:
==Python:==
def isValid(str):
stack = []
pattern_map = {')':'(',']':'[','}':'{'}
for c in str:
if c not in pattern_map:
stack.append(c)
elif not stack or pattern_map[c] != stack.pop():
return False
return not stack
==Java==
public boolean isValid(String str){ int length; do{ length = str.length(); str = str.replace("()","").replace("[]","").replace("{}",""); }while(length != str.length()); return str.length() == 0; }
Test
''' ************************** Author: PQ Date: 2018/7/27 Target: Stack ************************** ''' class Stack: ''' 實現棧的功能: _content:序列 _current:包含元素數 _size:棧大小 setempty >將棧置空 isEmpty >判斷棧是否為空 setSize >設定棧大小 isFull >判斷棧是否滿了 push >入棧 pop >出棧 show >顯示棧內容 showSpace >顯示還剩多少空間 ''' def __init__(self,size = 10): self._content = [] self._size = size self._current = 0 def setEmpty(self): self._content = [] self._current = 0 def isEmpty(self): if not self._content: return True else: return False def setSize(self,size): if size < self._current: for i in range(size, self._current)[::-1]: del self._content[i] self._current = size self._size = size def isFull(self): if self._current == self._size: return True else: return False def push(self, v): if len(self._content) < self._size: self._content.append(v) self._current = self._current + 1 else: print("Stack is Full") def pop(self): if self._content: self._current = self._current - 1 return self._content.pop() else: print("Stack is empty!") def show(self): print self._content def showSpace(self): print("Stack can still PUSH",self._size - self._current," elements") if __name__ == '__main__': print "Please use me as a module."