224. Basic Calculator

来源:互联网 发布:中南大学网络教育电话 编辑:程序博客网 时间:2024/06/16 14:45

  • Problem Description
  • Implementation By C

Problem Description

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"(8)" = 8"" = 0"2-(5-6)" = 3Note: Do not use the eval built-in library function.

This problem can be well solved by stack. We utilize two stacks with operation type stack and operand stack. When we meet with number, we push the whole number into operand stack. When we meet with operation and ‘(’ we push it to operation stack. When we meet across ‘)’ we need do operation pop operands and operation type from stacks until we meet with ‘(‘. In the end, we pop the operands and operation until there is no operation in operation stack.

Implementation By C++

class Solution {public:    int calculate(string s) {        stack<int> num;        stack<char> ope;        int str_len = s.size();        int res = 0;        int tmp = 0;        if(str_len == 0) return res;        for(int idx = 0; idx < str_len; idx++) {            if(isdigit(s[idx])) {                 tmp = tmp*10 + s[idx] - '0';                if(idx == str_len - 1 || !isdigit(s[idx+1])) {                    num.push(tmp);                     tmp = 0;                }                }                else if(s[idx] == ')') {                while(ope.top() != '(') {                    if(num.size() > 1) {                        int op1 = num.top();                        num.pop();                        int op2 = num.top();                        num.pop();                        char ope_type = ope.top();                        ope.pop();                        num.push(op2+op1*(ope_type == '+'?1:-1));                    }                }                ope.pop();            }            else if(s[idx] == '(')                 ope.push(s[idx]);            else if(s[idx] == '+' || s[idx] == '-') {                if(ope.size() > 0 && ope.top() != '(') {                    int op1 = num.top();                    num.pop();                    int op2 = num.top();                    num.pop();                    char ope_type = ope.top();                    ope.pop();                    num.push(op2+op1*(ope_type == '+'?1:-1));                                    }                ope.push(s[idx]);            }        }        while(ope.size() > 0) {            int op1 = num.top();            num.pop();            int op2 = num.top();            num.pop();            char ope_type = ope.top();            ope.pop();            num.push(op2+op1*(ope_type == '+'?1:-1));                     }         return num.top();    }};
原创粉丝点击