此博客为《代码随想录》栈与队列章节的学习笔记,主要内容为栈的应用相关的题目解析。
20. 有效的括号
class Solution:
def isValid(self, s: str) -> bool:
dic = {')':'(',']':'[','}':'{'}
stack = []
for c in s:
if stack and c in dic:
if stack.pop() != dic[c]:
return False
else:
stack.append(c)
return not stack
- 提前使用字典保存括号的对应关系(右括号为 key),避免代码使用
if-elif-else
过于冗长
1047. 删除字符串中的所有相邻重复项
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for c in s:
if stack and stack[-1] == c:
stack.pop()
else:
stack.append(c)
return ''.join(stack)
- 使用
stack[-1]
模拟栈的peek()
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
operations = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: int(a / b),
}
stack = []
for t in tokens:
if t in operations:
n2, n1 = stack.pop(), stack.pop()
stack.append(operations[t](n1, n2))
else:
stack.append(int(t))
return stack[0]
- 提前使用 lambda 表达式保存符号运算关系,避免代码使用
if-elif-else
过于冗长 - 题目中要求的除法为向零取整,例如
-3 / 2 = -1
,但 Python 中的整数除法//
为向下取整,因此上述代码汇总使用的方法为先进行浮点数除法,之后转化为int
,即int(a / b)
- 另:对于是整数的字符串,上述代码中直接使用
else
处理,但如果想要判断一个字符串是不是一个整数,不能直接使用str.isdigit()
,其只有在字符串中全部都为数字的情况下返回True
,因此对于负数不适用
# 可使用正则表达式,同时判断正负整数和浮点数
def is_valid_number(s):
return bool(re.match(r"^-?\d+(\.\d+)?$", s))