LeetCode OJ:Basic Calculator(基础计算器)
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
一个基本的计算器而已,可以使用两个栈来解决,下面这个方法是参考了别人的做法,当遇到左括号的时候要先考虑括号里面的东西,所以把前面的结果全部都入栈。遇到右括号的时候将左括号之前的栈的的东西拿出来计算再次得到临时的结果。这里由于
之后有+和减号,所以可以使用sign == -1来模拟减号。 这里的res实际上也相当于一个栈的角色:
1 class Solution { 2 public: 3 int calculate(string s) { 4 int sz = s.size(); 5 int left, right; 6 char optor = '0'; 7 stack<int> tokenStk; //注意这里是int 8 int res = 0; 9 int sign = 1; 10 for(int i = 0; i < sz; ++i){ 11 if(s[i] == '+') 12 sign = 1; 13 else if(s[i] == '-') 14 sign = -1; 15 else if(isdigit(s[i])){ 16 int tmpNum = 0; 17 for(int j = i; j < sz; ++j){ 18 if(isdigit(s[j])){ 19 tmpNum *= 10; 20 tmpNum += (s[j] - '0'); 21 i = j; 22 }else break; 23 } 24 res += sign * tmpNum; 25 }else if(s[i] == '('){ 26 tokenStk.push(res); 27 res = 0; 28 tokenStk.push(sign); 29 sign = 1; 30 }else if(s[i] == ')'){ 31 int tmpSign = tokenStk.top(); 32 tokenStk.pop(); 33 int left = tokenStk.top(); 34 tokenStk.pop(); 35 res = res * tmpSign + left; 36 sign = 1; 37 } 38 } 39 return res; 40 } 41 };
下面是java写的,不得不说java里面处理字符串的函数确实比c++要友好很多哈,代码如下所示:
1 public class Solution { 2 public int calculate(String s) { 3 int sz = s.length(); 4 int ret = 0; 5 int sign = 1; 6 int res = 0; 7 Stack<Integer> stk = new Stack<Integer>(); 8 for(int i = 0; i < sz; i++){ 9 if(s.charAt(i) == '+') 10 sign = 1; 11 else if(s.charAt(i) == '-') 12 sign = -1; 13 else if(Character.isDigit(s.charAt(i))){ 14 int beg = i; 15 while(i+1 < sz && Character.isDigit(s.charAt(i+1))) 16 i++; 17 res += sign * Integer.parseInt(s.substring(beg, i+1));//将数字分割开 18 }else if(s.charAt(i) == '('){ 19 stk.push(res); 20 stk.push(sign); 21 res = 0; 22 sign = 1; 23 }else if(s.charAt(i) == ')'){ 24 int tmpSign = stk.pop(); 25 int parLeft = stk.pop();//括号左边,也就是外面的值 26 res = parLeft + tmpSign * res;//暂时还是不用push的 27 }else//跳过空格 28 continue; 29 } 30 return res; 31 } 32 }