leetcode-244
Given a string s representing an expression, implement a basic calculator to evaluate it.
s consists of digits, '+', '-', '(', ')', and ' '
I build the calculator with recursive and stack. However, always got wrong result with parentheses ‘()’
what`s wrong with my code in helper func
func calculate(s string) int {
if len(s) == 0 {
return 0
}
return helper(s)
}
func helper(s string) int {
stack := make([]int, 0)
num := 0
sign := '+'
for len(s) > 0 {
c := s[0]
s = s[1:]
fmt.Println("======出栈======", string(c))
if c == '(' {
num = helper(s)
}
if (!isdigit(c) && c != ' ') || len(s) == 0 {
switch sign {
case '-':
// fmt.Println("======减法=======", sign)
stack = append(stack, -num)
case '+':
stack = append(stack, num)
case '*':
pre := stack[len(stack)-1] // top
stack = stack[:len(stack)-1] // pop
stack = append(stack, num*pre)
case '/':
pre := stack[len(stack)-1]
stack = stack[:len(stack)-1]
stack = append(stack, num/pre)
}
if c == ')' {
break
}
sign, _ = utf8.DecodeRune([]byte{c})
// fmt.Println(sign, c)
num = 0
}
if isdigit(c) {
num = num*10 + int(c-'0')
}
}
fmt.Println(stack)
return sum(stack)
}
func main() {
// wrong case as follows
// fmt.Println(calculate("1+(4+5+2) - 3"))
// fmt.Println(calculate("(1+(4+5+2)-3)+(6+8)"))
// fmt.Println(calculate(" ( 5*(4-2)+1-6)/5*2 "))
fmt.Println(calculate(" (12-1) + 12 "))
}
func sum(stack []int) int {
res := 0
for i := 0; i < len(stack); i++ {
res += stack[i]
}
return res
}
func isdigit(char byte) bool {
// char >= 48 && char <= 57
return char >= '0' && char <= '9'
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…