标签:
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 };
LeetCode OJ:Basic Calculator(基础计算器)
标签:
原文地址:http://www.cnblogs.com/-wang-cheng/p/4899299.html