20. 有效的括号
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
设置一个stack和括号的map
遍历s,如果s是左括号放入stack,如果是右括号看时候stack最后一个值是左括号对应的type,如果不是或者stack为空return false,检测完成则popstack的最后一个值。
遍历完成后检测是否stack是否为空 空的话就可以return true。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
hashtable={')':'(',']':'[','}':'{'}
left={'(','{','['}
right={')',']','}'}
stack=[]
for i in s:
if i in left:
stack.append(i)
elif i in right:
if not stack or stack[-1]!=hashtable[i]:
return False
stack.pop()
return True if not stack else False
- 时间复杂度:O(n)
- 空间复杂度:O(n)
1047. 删除字符串中的所有相邻重复项
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
建空stack
遍历s 如果stack为空或者stack最后一位不是i则appendi,如果最后一位==i则删除最后一位。
遍历完return结果。
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
stack=[]
for i in s:
if not stack or stack[-1]!=i:
stack.append(i)
elif stack[-1]==i:
stack.pop()
return ''.join(stack)
- 时间复杂度:O(n)
- 空间复杂度:O(n)
150. 逆波兰表达式求值
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
建立一个stack
遍历tokens,如果是数字就append进stack 如果是符号就进行计算,计算时 pop两个数字 因为除法有顺序 所以pop的第一个数字作为2 第二个数字作为1 进行计算 计算完放回进stack。 遍历结束后返回结果。 注意在python中 6/(-132)=-1而不是0
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
operator={'+','-','*','/'}
stack=[]
num1=None
num2=None
for i in tokens:
if i not in operator:
stack.append(int(i))
elif i in operator:
if i =="+":
num2=stack.pop()
num1=stack.pop()
stack.append(num1+num2)
elif i =="-":
num2=stack.pop()
num1=stack.pop()
stack.append(num1-num2)
elif i =="*":
num2=stack.pop()
num1=stack.pop()
stack.append(num1*num2)
elif i =="/":
num2=stack.pop()
num1=stack.pop()
stack.append(int((num1)/num2))
return stack.pop()
- 时间复杂度:O(n)
- 空间复杂度:O(n)