227. Basic Calculator II

来源:互联网 发布:物体识别软件 编辑:程序博客网 时间:2024/05/30 05:25

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7" 3/2 " = 1" 3+5 / 2 " = 5

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

class Solution {public:    int calculate(string s)    {        std::vector<int> operands;        std::vector<char> operators;        int i = 0;        int num;        while(s[i] != '\0')        {            while(s[i] == ' ')                i++;            if(s[i] <= '9' && s[i] >= '0')            {                num = 0;                do{                    num = num * 10 + s[i++] - '0';                }while(s[i] <= '9' && s[i] >= '0');                operands.push_back(num); //得到操作数            }            else if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')            {               while(operators.size() != 0)               {                  char op = operators.back();                  if(true == CompareOp(s[i], op))//s[i] > op                      break;                  operators.pop_back();                  int number_a, number_b;                  number_a = operands.back();                  operands.pop_back();                  number_b = operands.back();                  operands.pop_back();                  operands.push_back(GetResult(number_b, number_a, op));                }                operators.push_back(s[i++]);            }        }// end of while        while(operators.size() != 0)        {           char op = operators.back();           if(true == CompareOp(s[i], op))//s[i] > op               break;           operators.pop_back();           int number_a, number_b;           number_a = operands.back();           operands.pop_back();           number_b = operands.back();           operands.pop_back();           operands.push_back(GetResult(number_b, number_a, op));         }        return operands.back();    }    int GetResult(int a, int b, char op)    {        switch(op)        {            case '+': return a + b;            case '-' : return a - b;            case '*': return a * b;            case '/': return a / b;        }    }    bool CompareOp(char a, char b) //a > b, true    {        if((a == '*' || a == '/') && (b == '+' || b == '-'))            return true;        return false;    }};

写这个还是c++好用,毕竟有人家已经写好的vector容器可以用,不用去担心自己的数组是否会爆。

程序的主要主要利用的是堆, 利用堆将表达式转化为后序表达式,然后进行处理,由于转后序和计算可以合在一起,因此就只遍历了一遍。