码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Basic Calculator

时间:2015-06-09 16:40:54      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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

 Note: Do not use the eval built-in library function.

一个很详细的解释:http://www.geeksforgeeks.org/expression-evaluation/ 比这道题还难点

思路就是两个stack,一个存数字一个存符号。如果遇到数字直接存到数字stack;如果遇到符号,有几种情况:

1.当前符号比上一个符号优先级高,比如* 高于+,那么直接进栈

2.当前符号低于上一个,那么就要把所有已经在stack里面优先于当前符号的全算完,再推进当前符号

3.当前符号是“(”,直接push

4.当前符号是“)”,就要把所有“(”以前的符号全部算完

这道题只有“+”号与“-”号,不用判断符号的优先级。

 1 class Solution {
 2 public:
 3     int calculate(string s) {
 4         stack<int> stk_val;
 5         stack<char> stk_op;
 6         int res = 0, tmp;
 7         for (int i = 0; i <= s.length(); ++i) {
 8             //操作数
 9             if (i < s.length() && isdigit(s[i])) {
10                 res = 0;
11                 while (i < s.length() && isdigit(s[i])) {
12                     res *= 10;
13                     res += s[i++] - 0;
14                 }
15                 stk_val.push(res);
16             }
17             //运算符
18             if (i == s.length() || s[i] == + || s[i] == - || s[i] == )) {
19                 while (!stk_op.empty() && stk_op.top() != () {
20                     tmp = stk_val.top();
21                     stk_val.pop();
22                     if (stk_op.top() == +) stk_val.top() += tmp;
23                     else if (stk_op.top() == -) stk_val.top() -= tmp;
24                     stk_op.pop();
25                 }
26                 if (i == s.length()) break;
27                 else if (s[i] == )) stk_op.pop();
28                 else stk_op.push(s[i]);
29             } else if (s[i] == () {
30                 stk_op.push(s[i]);
31             }
32         }
33         return stk_val.top();
34     }
35 };

 

LintCode上有一道相同的题,但是运算符不仅包含"+"、"-",还包含了 "*" 和 "/",不过不用自己解析操作数了。

Expression Evaluation

Given an expression string array, return the final result of this expression

For the expression 2*6-(23+7)/(1+2), input is

[
  "2", "*", "6", "-", "(",
  "23", "+", "7", ")", "/",
  (", "1", "+", "2", ")"
],

return 2

Note

The expression contains only integer+-*/().

 1 class Solution {
 2 public:
 3     /**
 4      * @param expression: a vector of strings;
 5      * @return: an integer
 6      */
 7     int calulate(int a, int b, const string &op) {
 8         if (op == "+") return a + b;
 9         else if (op == "-") return a - b;
10         else if (op == "*") return a * b;
11         else return a / b;
12     }
13     bool isOK(const string &op1, const string &op2) {
14         if (op1 == "*" || op1 == "/" || op2 == ")") return true;
15         else return op2 == "+" || op2 == "-";
16     }
17     int evaluateExpression(vector<string> &expression) {
18         // write your code here
19         if (expression.empty()) return 0;
20         stack<int> stk_val;
21         stack<string> stk_op;
22         for (int i = 0; i <= expression.size(); ++i) {
23             if (i < expression.size() && isdigit(expression[i][0])) {
24                 stk_val.push(atoi(expression[i].c_str()));
25             } else if (i == expression.size() || expression[i] != "(") {
26                 while (!stk_op.empty() && stk_op.top() != "(" 
27                 && (i == expression.size() || isOK(stk_op.top(), expression[i]))) {
28                     int tmp = stk_val.top();
29                     stk_val.pop();
30                     stk_val.top() = calulate(stk_val.top(), tmp, stk_op.top());
31                     stk_op.pop();
32                 }
33                 if (i == expression.size()) break;
34                 else if (expression[i] == ")") stk_op.pop();
35                 else stk_op.push(expression[i]);
36             } else {
37                 stk_op.push(expression[i]);
38             }
39         }
40         return stk_val.top();
41     }
42 };

 

[LeetCode] Basic Calculator

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4563780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!