当前位置:   article > 正文

代码随想录算法训练营第十天| 第五章 栈与队列part02

代码随想录算法训练营第十天| 第五章 栈与队列part02

今天的三道题仍然是关于栈与队列,三道题都还算比较常规

直接贴代码咯

第一道: 20. 有效的括号

  1. class Solution:
  2. def isValid(self, s: str) -> bool:
  3. ## 使用栈和队列
  4. stack = []
  5. s = list(s)
  6. for i in s:
  7. if i == "{" or i == "[" or i == "(":
  8. stack.append(i)
  9. else:
  10. if len(stack) == 0:
  11. return False
  12. a = stack.pop()
  13. if i == "]" and a != "[":
  14. return False
  15. if i == "}" and a != "{":
  16. return False
  17. if i == ")" and a != "(":
  18. return False
  19. if len(stack) != 0:
  20. return False
  21. return True

第二道:1047. 删除字符串中的所有相邻重复项

  1. class Solution:
  2. def removeDuplicates(self, s: str) -> str:
  3. stack = []
  4. s = list(s)
  5. for i in s:
  6. if stack == [] or stack[-1] != i:
  7. stack.append(i)
  8. else:
  9. stack.pop()
  10. return "".join(stack)

第三道:150. 逆波兰表达式求值

  1. class Solution:
  2. def evalRPN(self, tokens: List[str]) -> int:
  3. stackNum = []
  4. for i in tokens:
  5. if i[0] == '-' and i[1:].isdigit():
  6. stackNum.append(i)
  7. elif i.isdigit():
  8. stackNum.append(i)
  9. else:
  10. temp1 = int(stackNum.pop())
  11. temp2 = int(stackNum.pop())
  12. if i == "+":
  13. stackNum.append(temp2+temp1)
  14. if i == "-":
  15. stackNum.append(temp2-temp1)
  16. if i == "*":
  17. stackNum.append(temp2*temp1)
  18. if i == "/":
  19. if temp2//temp1 < 0:
  20. if temp2//temp1 == temp2 / temp1:
  21. stackNum.append(temp2//temp1)
  22. else:
  23. stackNum.append(temp2//temp1 + 1)
  24. else:
  25. stackNum.append(temp2//temp1)
  26. return int(stackNum[0])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/185555
推荐阅读
相关标签
  

闽ICP备14008679号