今天是day9:
题目一:
匹配括号:
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 stack[-1] != item:
return False
else:
stack.pop()
return True if not stack else False
class Solution:
def isValid(self, s: str) -> bool:
stcak = []
mapping = {
'(':')',
'[':']',
'{':'}',
}
for item in s:
"如果在key中就将将它追加到栈中"
if item in mapping.keys():
stcak.append(mapping[item])
elif not stcak or stcak[-1] != item:
return False
else:
//否则弹出
stcak.pop()
return True if not stcak else False
func isValid(s string) bool {
//用切片模拟栈
stack := make([]rune,0)
//m用于记录某个右括号对应的左括号
m:=make(map[rune]rune)
m[')'] = '('
m['}'] = '{'
m[']'] = '['
//遍历字符串中的rune
for _,c := range s {
//左括号直接入栈
if c == '(' || c == '[' || c == '{' {
stack = append(stack,c)
} else {
//如果右括号,先判断栈内是否还有元素
if len(stack) == 0{
return false
}
//再判断栈顶元素是否能匹配
peek := stack[len(stack)-1]
if peek != m[c] {
return false
}
//模拟栈顶弹出
stack = stack[:len(stack)-1]
}
}
//此时栈内无元素,即完全匹配
return len(stack) == 0
}
题目二:删除字符串中的所有相邻重复项
class Solution:
def removeDuplicates(self, s: str) -> str:
res = list()
for item in s:
if res and res[-1] == item:
res.pop()
else:
res.append(item)
return "".join(res)
class Solution:
def removeDuplicates(self, s: str) -> str:
res = list(s)
slow = fast = 0
length = len(res)
while fast < length:
//如果一样直接替换,不一样会把后面的填在slow的位置
res[slow] = res[fast]
//如果发现和前一个一样,就退一格指针
if slow > 0 and res[slow] == res[slow - 1]:
slow -=1
else:
slow+=1
fast +=1
return ''.join(res[0:slow])
func removeDuplicates(s string) string {
var stack []byte
for i:=0;i< len(s);i++{
//栈不空且与栈顶元素不等
if len(stack) > 0 && stack[len(stack)-1] == s[i] {
//弹出栈顶元素并忽略当前元素(s[i])
stack = stack[:len(stack) - 1]
}else{
//入栈
stack = append(stack,s[i])
}
}
return string(stack)
}
题目三:逆波兰表达式
from operator import add,sub,mul
class Solution:
"从库中引用这些操作并通过map将其绑定在对应的字符上"
op_map = {'+':add,'-':sub,'*':mul,'/':lambda x,y: int(x / y)}
def evalRPN(self, tokens: List[str]) -> int:
"声明一个空栈"
stack = []
"遍历并判断,并达到将满足这些运算符都加入到栈中的目的"
for token in tokens:
if token not in {'+','-','*','/'}:
stack.append(int(token))
else:
"否则就弹出"
op2 = stack.pop()
op1 = stack.pop()
"从 op_map 中获取相应的操作函数,并将栈顶的两个操作数传递给这个操作函数,执行相应的运算,并将结果压入栈中。"
stack.append(self.op_map[token](op1,op2))
return stack.pop()
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item not in {"+","-","*","/"}:
stack.append(item)
else:
first_num,second_num = stack.pop(),stack.pop()
stack.append(
"第一个出来的在运算符后面"
int(eval(f'{second_num} {item} {first_num}'))
)
"如果一开始只有一个数那么就是字符串形式的"
return int(stack.pop())
func evalRPN(tokens []string) int {
stack := []int{}
for _,token := range tokens{
//行代码将当前遍历到的 token 转换为整数 val。strconv.Atoi 函数用于将字符串转换为整数。如果转换成功,err 将为 nil,否则将是一个非 nil 的错误。
val,err := strconv.Atoi(token)
if err == nil {
//如果当前 token 是一个操作数,将其压入栈中。
stack = append(stack,val)
}else{
//否则从栈中取出栈顶的两个操作数,分别赋值给 num1 和 num2。
num1,num2 := stack[len(stack) - 2],stack[len(stack) -1]
//将栈顶的两个操作数从栈中移除,即将栈的长度减去 2。
stack = stack[:len(stack)-2]
switch token {
case "+":
stack = append(stack,num1+num2)
case "-":
stack = append(stack,num1-num2)
case "*":
stack = append(stack,num1*num2)
case "/":
stack = append(stack,num1/num2)
}
}
}
return stack[0]
}