第五章 栈与队列part02

本文介绍了如何使用栈数据结构解决编程问题,包括检查有效括号、删除字符串中的相邻重复字符以及计算逆波兰表达式的值。作者通过示例代码展示了栈在这些场景中的应用。
摘要由CSDN通过智能技术生成

20. 有效的括号

  • 用数组模拟出一个栈即可
func isValid(s string) bool {
	piars := map[byte]byte{
		')': '(',
		']': '[',
		'}': '{',
	}
	stack := make([]byte, 10010)
	index := -1
	sb := []byte(s)
	for _, char := range sb {
		if val, ok := piars[char]; ok {
			if index < 0 {
				return false
			}
			// 需要匹配
			topVal := stack[index]
			if topVal != val {
				return false
			} else {
				index--
			}
		} else {
			index++
			stack[index] = char
		}
	}
	return index == -1
}

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

func removeDuplicates(s string) string {
	stack := make([]byte, 200010)
	index := -1
	for i := 0; i < len(s); i++ {
		char := s[i]
		if index == -1 {
			// push
			index++
			stack[index] = char
			continue
		}
		topVal := stack[index]
		if topVal == char {
			// pop
			index--
		} else {
			// push
			index++
			stack[index] = char
		}
	}
	res := make([]byte, index+1)
	for i := 0; i <= index; i++ {
		res[i] = stack[i]
	}
	return string(res)
}

150. 逆波兰表达式求值

  • 注意这里给的已经是后缀表达式了,不用考虑中缀转后缀问题

var nums []string
var numsIndex int

var ops []string
var opsIndex int

func pushNum(x string) {
	numsIndex++
	nums[numsIndex] = x
}
func popNum() string {
	// check
	x := nums[numsIndex]
	numsIndex--
	return x
}
func pushOp(c string) {
	opsIndex++
	ops[opsIndex] = c
}
func popOp() string {
	x := ops[opsIndex]
	opsIndex--
	return x
}
func topOp() string {
	return ops[opsIndex]
}
func parse(a, b, op string) string {
	x1, _ := strconv.Atoi(b)
	x2, _ := strconv.Atoi(a)
	switch op {
	case "+":
		return strconv.Itoa(x1 + x2)
	case "-":
		return strconv.Itoa(x1 - x2)
	case "*":
		return strconv.Itoa(x1 * x2)
	case "/":
		return strconv.Itoa(x1 / x2)

	}
	return ""
}
func evalRPN(tokens []string) int {
	// init
	nums = make([]string, 10010)
	numsIndex = -1
	ops = make([]string, 10010)
	opsIndex = -1
	// pior: + - * /
	operations := map[string]int{
		"+": 1, "-": 2, "*": 3, "/": 4, "#": 5,
	}
	//pushOp("#")
	for _, token := range tokens {
		if _, ok := operations[token]; ok {
			res := parse(popNum(), popNum(), token)
			pushNum(res)
			//pushOp(token)
		} else {
			pushNum(token)
		}
	}
	res, _ := strconv.Atoi(popNum())
	return res
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

左手八嘎呀路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值