yankewei / LeetCode

LeetCode 问题的解决方法
MIT License
6 stars 0 forks source link

基本计算器 II #124

Open yankewei opened 3 years ago

yankewei commented 3 years ago

给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

整数除法仅保留整数部分。

示例 1:

输入:s = "3+2*2"
输出:7

示例 2:

输入:s = " 3/2 "
输出:1

示例 3:

输入:s = " 3+5 / 2 "
输出:5

提示:

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/basic-calculator-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

yankewei commented 3 years ago

用栈模拟即可

需要注意数字是可能大于10的

func calculate(s string) int {
    s = strings.ReplaceAll(s, " ", "")
    slice := strings.Split(s, "")
    var stack []string

    for i := 0; i < len(slice); i++ {
    if slice[i] == "+" || slice[i] == "-" {
        stack = append(stack, string(s[i]))
        index, numeric := getNumeric(i+1,slice)
        stack = append(stack, numeric)
        i = index
    } else if slice[i] == "*" || slice[i] == "/" {
        // 从栈中拿最后一个元素
        num,_ := strconv.Atoi(stack[len(stack)-1])
        index, numeric := getNumeric(i+1, slice)
        nextNum, _ := strconv.Atoi(numeric)
        if slice[i] == "*" {
        stack[len(stack)-1] = strconv.Itoa(num * nextNum)
        } else {
        stack[len(stack)-1] = strconv.Itoa(num / nextNum)
        }
        i = index
    } else {
        index, numeric := getNumeric(i,slice)
        i = index
        stack = append(stack, numeric)
    }
    }
    ret,_ := strconv.Atoi(stack[0])
    for i := 1; i < len(stack); i++ {
    if stack[i] == "+" {
        cur,_ := strconv.Atoi(string(stack[i+1]))
        ret += cur
    } else {
        cur,_ := strconv.Atoi(string(stack[i+1]))
        ret -= cur
    }
    i++
    }

    return ret
}

func getNumeric(i int, str []string) (index int, ret string) {
    var numeric []string
    for i < len(str) {
        if str[i] == "+" || str[i] == "-" || str[i] == "/" || str[i] == "*" {
        break
        }
        numeric = append(numeric, str[i])
        i++
    }
    return i-1, strings.Join(numeric, "")
}