Advertisement
Guest User

Untitled

a guest
Jul 4th, 2015
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     /**
  4.      * @param expression: a vector of strings;
  5.      * @return: an integer
  6.      */
  7.     int evaluateExpression(vector<string> &expression) {
  8.         // write your code here
  9.        
  10.         int n=expression.size();
  11.         opands.push(0);
  12.         for(int i=0;i<n;i++) {
  13.             if(isdigit(expression[i][0])) { // hacky: only check the first char
  14.                 opands.push(atoi(expression[i].c_str()));
  15.             } else if(expression[i]==")") {
  16.                 while(ops.top()!='(') {
  17.                     computeAndPush();
  18.                 }
  19.                 ops.pop();
  20.             } else {
  21.                 if(!ops.empty() && hasPrecedence(ops.top(), expression[i][0])) {
  22.                     computeAndPush();
  23.                 }
  24.                 ops.push(expression[i][0]);
  25.             }
  26.         }
  27.        
  28.         while(!ops.empty()) {
  29.             computeAndPush();
  30.         }
  31.         return opands.top();
  32.     }
  33.    
  34.     void computeAndPush() {
  35.         int opand2=opands.top(); opands.pop();
  36.         int opand1=opands.top(); opands.pop();
  37.         char op=ops.top(); ops.pop();
  38.         switch(op){
  39.             case '+': opands.push(opand1+opand2); break;
  40.             case '-': opands.push(opand1-opand2); break;
  41.             case '*': opands.push(opand1*opand2); break;
  42.             case '/': opands.push(opand1/opand2); break;
  43.         }  
  44.     }
  45.    
  46.     bool hasPrecedence(char op1, char op2) {
  47.         if(op2=='(') return false;
  48.         if((op2=='*' || op2=='/') && (op1=='+' || op1=='-')) return false;
  49.         return true;
  50.     }
  51. private:
  52.     stack<char> ops;
  53.     stack<int> opands;
  54. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement