栈——简单
1047 删除字符串中所有相邻重复项
class Solution(object):
def removeDuplicates(self, S):
output = []
for s in S:
if output and s == output[-1]:
output.pop()
else:
output.append(s)
return ''.join(output)
20 有效的括号
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
# 用栈保存 (,[,{
stack = []
# map中保存的是 ):(, ]:[,}:{
# 当遍历到 )时候就会去map中找对应的value,也就是(
# 再用这个value和stack弹出的元素比较,如果相等则匹配上,不等则返回false
# 这里也可以用数组来存,我为了简单就用map表示了
d = {")":"(", "]":"[","}":"{"}
# 开始遍历字符串
for i in s:
# 如果map中不包含 (,[,{,就将这个字符放入栈中
if i not in d:
stack.append(i)
else:
# 如果遍历的字符不再map中,也就是说这个字符是),],},那么就要跟栈中的元素比较
# 首先要判断栈是否为空,如果输入的字符是 )() ,那么当遍历到第一个)时,栈为空
if not stack:
return False
# 取出栈顶的元素
tmp = stack.pop()
# 假设当前遍历到的元素是 ],那么从map中取到的value就是 [
# 如果栈顶的元素是 (,则不匹配返回false,否则继续
if d[i]!=tmp:
return False
# 返回的时候还要判断栈是否为空
# 如果输入的字符串是 (((,那么最后栈就不为空
return True if not stack else False