LeetCode--20.有效的括号
有效的括号
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."
posted on 2018-11-25 22:32 Kn0w_N0ThInG 阅读(116) 评论(0) 编辑 收藏 举报