leetcode刷题笔记 224题 基本计算器

leetcode刷题笔记 224题 基本计算器

源地址:224. 基本计算器

问题描述:

实现一个基本的计算器来计算一个简单的字符串表达式的值。

字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。

示例 1:

输入: "1 + 1"
输出: 2
示例 2:

输入: " 2-1 + 2 "
输出: 3
示例 3:

输入: "(1+(4+5+2)-3)+(6+8)"
输出: 23
说明:

你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。

//使用栈搭配模式匹配处理
import scala.collection.mutable
object Solution {
    def calculate(s: String): Int = {
        //存储()情况
        val stack = new mutable.Stack[Int]()
        //当前计算结果
        var res = 0
        //操作数
        var operand = 0
        //符号正负情况
        var sign = 1
        //println(s.replace(" ",""))
        
        //需注意对空格的处理
        for (i <- 0 to s.length-1) {
            val ch = s.charAt(i)
            ch match {
                //加法
                case '+' => {
                    //println("operand: " + operand)
                    res += sign * operand
                    sign = 1
                    operand = 0
                }
                //减法
                case '-' => {
                    //println("operand: " + operand)
                    res += sign * operand
                    sign = -1
                    operand = 0
                }
                //左括号 当前res和符号入栈 重新计算
                case '(' => {
                    stack.push(res)
                    stack.push(sign)
                    res = 0
                    sign = 1
                }
                //右括号 计算括号内部值 将之前保存的值弹出 参于计算
                case ')' => {
                    res += sign * operand
                    res *= stack.pop()
                    res += stack.pop()
                    operand = 0
                    sign = 1
                }
                //空字符处理
                case ' ' =>
                //
                case _ => {
                    operand = 10 * operand + (ch - '0').toInt
                    //println(operand)
                }          
            }
        }
        
        return res + sign * operand
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13791665.html