20 | Valid Parentheses | 33.90% | 检查正反括号是否配对完整 |
python中in的用法:for char in s |
replace():str.replace(old, new[, max]) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 8 21:03:48 2018
@author: vicky
"""
#先顺序找到左括号,在反序查找右括号
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
d={'(':')','{':'}','[':']'} #dict{keys:values}
p=[] #[]为list,可以用pop;“”为string,不能用pop。所以p=[]
#range(a,b,c),从a到b间隔为c,数组写法是array[a:b:c]
for char in s:
#字典的key:value提出方法:d.keys(),d.values()
if char in d.keys(): #或者 char in '([{':
p.append(char)
else:
#字典pop用法:dict.pop(key)删去一对key和value
#list pop用法:
#list.pop(obj=list[-1])移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
#p.pop()=p.pop(-1),移除列表中的最后一个元素,并且返回最后一个元素。运行后的p=原来的p删掉最后一个元素.
if p==[] or d[p.pop()]!=char: #判断的同时p的值已经删除了最后一个元素
return False
return p==[]
s="([)]" #false
s="([])" #true
s="]"
Solution().isValid(s)
class Solution(object):
def isValid(self, s):
n = len(s)
while(n != 0 and n%2 == 0):
# 注意替换函数replace的运用:
# str.replace(old, new[, max])
# old -- 将被替换的子字符串。
# new -- 新字符串,用于替换old子字符串。
# max -- 可选字符串, 替换不超过 max 次
s = s.replace("()", "")
s = s.replace("[]", "")
s = s.replace("{}", "")
# breaks while loop if string was not altered during current pass
if n>len(s):
n=len(s)
else:
n=0
return len(s) == 0
#最简洁,但是运行速度慢
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
if len(s)%2!= 0:
return False
while '()' in s or '{}' in s or '[]' in s:
s = s.replace('{}','').replace('()','').replace('[]','')
return len(s)==0