题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4

package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 返回表达式的值
 * @param s string字符串 待计算的表达式
 * @return int整型
 */
func solve(s string) int {

	cal := func(ops []int, nums []int) int {
		if len(nums) <= 0 {
			return 0
		}
		newOps := make([]int, 0)
		newNums := make([]int, 0)
		newNums = append(newNums, nums[0])
		for i := 0; i < len(ops); i++ {
			if ops[i] == 2 {
				nums[i+1] = nums[i] * nums[i+1]
				newNums[len(newNums)-1] = nums[i+1]
			} else {
				newOps = append(newOps, ops[i])
				newNums = append(newNums, nums[i+1])
			}
		}

		for i := 0; i < len(newOps); i++ {
			if newOps[i] == 0 {
				newNums[i+1] = newNums[i] + newNums[i+1]
			} else {
				newNums[i+1] = newNums[i] - newNums[i+1]
			}
		}
		return newNums[len(newNums)-1]
	}

	var dfs func(ss string, st int, en int) (int, int)
	dfs = func(ss string, st int, en int) (int, int) {
		ops := make([]int, 0)
		nums := make([]int, 0)
		curV := 0
		hasV := false
		for i := st; i <= en; {
			if ss[i] >= '0' && ss[i] <= '9' {
				curV = curV*10 + int(ss[i]) - '0'
				hasV = true
			} else {
				if ss[i] == '(' {
					val, next := dfs(ss, i+1, en)
					nums = append(nums, val)
					i = next
					continue
				} else if ss[i] == ')' {
					if hasV {
						nums = append(nums, curV)
					}
					return cal(ops, nums), i + 1
				} else {
					if hasV {
						nums = append(nums, curV)
					}
					op := 0
					if ss[i] == '+' {
						op = 0
					} else if ss[i] == '-' {
						op = 1
					} else {
						op = 2
					}
					ops = append(ops, op)
					curV = 0
					hasV = false
				}
			}
			i++
		}
		if hasV {
			nums = append(nums, curV)
		}
		return cal(ops, nums), en + 1
	}
	res, _ := dfs(s, 0, len(s)-1)
	return res
	// write code here
}

全部评论

相关推荐

吃不饱的肱二头肌很想退休:tnnd 我以为选妹子呢,亏我兴高采烈的冲进来😠
投递快手等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务