Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

algorithm - build Calculator with recursive and stack , always got wrong result with parentheses ‘()’,what`s wrong

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'
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Issue is appearing like you are not keeping the reference of operator before (. For e.g. 2-(2+2) So, it appearing that you have calculated (2+2) correctly but have not push "-4" is stack.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...