LC20. 有效的括号:
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for item in s:
if item == "(":
stack.append(")")
elif item == "{":
stack.append("}")
elif item == "[":
stack.append("]")
elif not stack or item != stack[-1]:
return False
else:
stack.pop()
return True if not stack else False
判断三种情况:1.左方向符号多了 所以不匹配。 2. 括号类型不匹配。3. 右方向括号多余所以不匹配
LC1047 删除字符串中的所有相邻重复项:
class Solution:
def removeDuplicates(self, s: str) -> str:
res =list()
for i in s:
if res and res[-1] == i:
res.pop()
else:
res.append(i)
return "".join(res)
用数组模拟栈,额外需要一个数组储存,最后需要变为字符串,都是O(N)的操作,总体O(N)。
LC150 逆波兰表达式求值
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item not in {"+","-","*","/"}:
stack.append(item)
else:
nums1, nums2 = stack.pop(), stack.pop()
stack.append(
int(eval(f'{nums2} {item} {nums1}'))
)
return int(stack.pop())
先搞清楚后缀表达式。遍历字符,如果有数字,就加进栈里,没有的话就根据运算符号直接进行运算。最后返回stack。注意要转化成int类型。