20. 有效的括号
class Solution(object):
def isValid(self, s):
stack = []
for x in s:
if x == '(':
stack.append(')')
elif x == '{':
stack.append('}')
elif x == '[':
stack.append(']')
else:
if not stack:
return False
elif stack:
a = stack.pop()
if x != a:
return False
if stack:
return False
return True
394. 字符串解码
题目链接:394. 字符串解码
使用栈:遍历字符串,如果遇到的不是’]',就把元素加到栈里,如果遇到']',就将栈中’['之前的元素(即字符)提取出来作为要重复的元素,把'['弹出后,再把遇到的数字给提取出来,最终实现一次重复的操作。
class Solution(object):
def decodeString(self, s):
stack = []
for i in s:
if i != ']':
stack.append(i)
elif i == ']':
strs = ''
repeat = ''
while stack[-1] != '[':
strs = stack.pop() + strs
stack.pop() # 把'['弹出
while stack and stack[-1].isdigit():
repeat = stack.pop() + repeat
stack.append(int(repeat) * strs)
return ''.join(stack)