LeetCode-20-Valid-Parentheses 栈 水题 Python 列表删除操作
2017-09-10 17:26
453 查看
判断括号合法性,用个栈就行了
Python里List 的pop,remove,del用法:
a.pop()直接pop最后一个,x=a.pop(3)是pop下标为3的数,同时返回这个数x
a.remove(3)是去掉第一个值为3的node
del a[3]就是删除下标为3的数,这里也可以删除一个区间a[1,3]
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
Len=len(s)
a=0
b=0
c=0
stack=[]
cnt=0
if Len<=1:return False
for i in range(Len):
if s[i]==']':
if cnt>0 and stack[cnt-1]=='[':
#stack.pop()
del stack[cnt-1]
cnt-=1
else: return False
elif s[i]=='}':
if cnt>0 and stack[cnt-1]=='{':
stack.pop()
cnt-=1
else: return False
elif s[i]==')':
if cnt>0 and stack[cnt-1]=='(':
stack.pop()
cnt-=1
else: return False
elif s[i]=='[' or s[i]=='{' or s[i]=='(':
stack.append(s[i])
cnt+=1
if cnt!=0 : return False
return True
Python里List 的pop,remove,del用法:
a.pop()直接pop最后一个,x=a.pop(3)是pop下标为3的数,同时返回这个数x
a.remove(3)是去掉第一个值为3的node
del a[3]就是删除下标为3的数,这里也可以删除一个区间a[1,3]
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
Len=len(s)
a=0
b=0
c=0
stack=[]
cnt=0
if Len<=1:return False
for i in range(Len):
if s[i]==']':
if cnt>0 and stack[cnt-1]=='[':
#stack.pop()
del stack[cnt-1]
cnt-=1
else: return False
elif s[i]=='}':
if cnt>0 and stack[cnt-1]=='{':
stack.pop()
cnt-=1
else: return False
elif s[i]==')':
if cnt>0 and stack[cnt-1]=='(':
stack.pop()
cnt-=1
else: return False
elif s[i]=='[' or s[i]=='{' or s[i]=='(':
stack.append(s[i])
cnt+=1
if cnt!=0 : return False
return True
相关文章推荐
- 【LeetCode 20】Valid Parentheses(Python)
- Python中的列表(添加二元列表、连接、查找、排序、反序、赋值、删除、分片操作、负索引、)
- [LeetCode] 82. Remove Duplicates from Sorted List II 从分类列表中删除重复项目 II @python
- 【python】列表的删除操作
- [leetcode:python]20.Valid Parentheses
- Python3列表元素的修改,添加( append(),inset() )和删除( del,pop(),remove() )操作
- python写算法题:leetcode: 20. Valid Parentheses
- LeetCode 20 Valid Parentheses (C,C++,Java,Python)
- LeetCode 20 — Valid Parentheses(C++ Java Python)
- leetcode 20. Valid Parentheses——python(easy)——使用了堆栈
- 20. Valid Parentheses Leetcode Python
- python 列表的操作(添加删除)列表和元组的区别
- Python编程之列表操作实例详解【创建、使用、更新、删除】
- python列表操作实例源码讲解(创建、使用、更新、删除)
- LeetCode@Stack_20_Valid_Parentheses
- leetcode 20|22|32. Valid Parentheses 22. Generate Parentheses 32. Longest Valid Parentheses
- 【leetcode】20. Valid Parentheses(Python & C++)
- python入门之列表list删除操作
- 20. Valid Parentheses leetcode Python 2016 new Season
- [转]python文件操作/打开/删除文件/压缩文件