20 有效的括号
解题思路
这个就是很简单的用list来代替栈
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=[]
for i in s:
if len(stack)==0:
stack.append(i)
else:
if stack[-1]=="(" and i ==")" or stack[-1]=="[" and i =="]" or stack[-1]=="{" and i =="}":
stack.pop()
else:
stack.append(i)
if len(stack)==0:
return True
else:
return False
if __name__=="__main__":
solu=Solution()
print(solu.isValid("([[[]]])}"))
1047 删除字符串中的所有相邻重复项
解题思路
这题也异常简单,我只能说选好数据结构,肝题速度糠吃糠吃
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
stack=[]
for i in s:
if len(stack)==0:
stack.append(i)
else:
if stack[-1]==i:
stack.pop()
else:
stack.append(i)
return "".join(stack)
if __name__=="__main__":
solu=Solution()
print(solu.removeDuplicates("abbaca"))
150 逆波兰表达式求值
解题思路
后序,但是我这个本地上正确leetcode跑不通
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack=[]
for i in tokens:
if i not in {"+","-","*","/"}:
stack.append(int(i))
else:
l2=stack.pop()
l1=stack.pop()
if i =="+":
res=l1+l2
elif i=="-":
res=l1-l2
elif i=="*":
res=l1*l2
else:
res=l1/l2
stack.append(res)
return int(round(stack[-1]))
if __name__=="__main__":
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
solu=Solution()
print(solu.evalRPN(tokens))