题解 | #四则运算#单栈解法
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
package main import ( "fmt" // "sort" "strings" "bufio" "os" // "strconv" ) func main(){ input := bufio.NewScanner(os.Stdin) input.Scan() data := input.Text() a := strings.Replace(data, "{", "(", -1) b := strings.Replace(a, "}", ")", -1) c := strings.Replace(b, "[", "(", -1) d := strings.Replace(c, "]", ")", -1) // fmt.Println(d) fmt.Println(cal(d)) } func cal(s string)int{ // fmt.Println(s, len(s)) num := 0 res := 0 sign := byte('+') if s[0]=='-'{ sign=byte('-') } stack := []int{} for i := 0;i<len(s);i++{ if isDigit(s[i]){ num = num*10 + int(s[i]-'0') } if s[i]=='(' { count := 1 j := i+1 for count>0{ if s[j]=='('{ count++ }else if s[j]==')'{ count-- } j++ } num = cal(s[i+1:j-1]) i = j-1 } if !isDigit(s[i]) || i == len(s)-1{ if sign == '+'{ stack = append(stack, num) }else if sign == '-'{ stack = append(stack, -num) }else if sign == '*'{ stack[len(stack)-1] *= num }else if sign == '/'{ stack[len(stack)-1] /= num } sign = s[i] num = 0 } if s[i]==')'{ continue } } for _,i := range stack{ res += i } return res } func isDigit(n byte)bool{ if n>='0'&&n<='9'{ return true }else{ return false } }