题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
package main
import "strconv"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
var m = map[string]int{
"+": 1,
"-": 1,
"*": 2,
"/": 2,
}
func solve( s string ) int {
// write code here
nums := make([]int, 0)
opts := make([]string, 0)
i := 0 ;
nums = append(nums, 0)
for i < len(s) {
ch := string(s[i])
if ch == "(" {
opts = append(opts, ch)
} else if ch == ")"{
nums, opts = calc(nums, opts, "")
if len(opts) > 0 && opts[len(opts) - 1] == "(" {
opts = opts[0:len(opts) - 1]
}
} else if isNumber(ch) {
j := i+1
for j < len(s) && isNumber(string(s[j])){
j++
}
t := s[i:j]
num, _ := strconv.Atoi(t)
nums = append(nums, num)
i = j
continue
} else {
if len(opts) == 0 {
opts = append(opts, ch)
} else if len(opts)>0 {
opt := opts[len(opts) - 1]
if m[ch] > m[opt] {
opts = append(opts, ch)
} else {
nums, opts = calc(nums, opts, ch)
opts = append(opts, ch)
}
}
}
i++
}
nums, opts = calc(nums, opts, "")
return nums[len(nums) - 1]
}
func isNumber(ch string) bool {
if ch >= "0" && ch <= "9" {
return true
}
return false
}
func calc(nums []int, opts []string, outSide string) ([]int,[]string) {
for len(opts) > 0 && len(nums) > 1 {
ch := opts[len(opts) - 1]
if ch == "(" {
return nums, opts
}
if outSide != "" && m[ch] < m[outSide] {
return nums, opts
}
opts = opts[0:len(opts) - 1]
num1 := nums[len(nums) - 1]
num2 := nums[len(nums) - 2]
nums = nums[0:len(nums) - 2]
res := 0
if ch == "+" {
res = num2 + num1
} else if ch == "-" {
res = num2 - num1
} else if ch == "*" {
res = num2 * num1
} else if ch == "/" {
res = num2 / num1
}
nums = append(nums, res)
}
return nums, opts
}