技巧
栈
思路
遇到数字就压栈 遇到操作符就拿栈顶两个进行运算 然后再把结果压栈
实现
package main import ( "strconv" ) /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 给定一个后缀表达式,返回它的结果 * @param str string字符串 * @return long长整型 */ // 逆波兰运算 func legalExp( str string ) int64 { // write code here stack := make([]int64, 0) numstr := "" for i := 0; i < len(str); i ++ { if str[i] == '#' { num, _ := strconv.Atoi(numstr) stack = append(stack, int64(num)) numstr = "" }else if str[i] == '+' { top1 := stack[len(stack) - 1] top2 := stack[len(stack) - 2] stack = stack[:len(stack) - 2] stack = append(stack, top1 + top2) }else if str[i] == '-' { top1 := stack[len(stack) - 1] top2 := stack[len(stack) - 2] stack = stack[:len(stack) - 2] stack = append(stack, top2 - top1) }else if str[i] == '*' { top1 := stack[len(stack) - 1] top2 := stack[len(stack) - 2] stack = stack[:len(stack) - 2] stack = append(stack, top1 * top2) }else { numstr += string(str[i]) } } return stack[0] }