Leetcode 227 Basic Calculator II

来源:互联网 发布:ibm公司软件 编辑:程序博客网 时间:2024/05/17 09:08

1. 问题描述

  给遗传字符串类型的表达式,计算表达式的值。表达式只包含+、-、*、/和空格。
  que


2. 方法与思路

  此题和Basic Calculator I类似,只是左右括号换成了乘除符号。基本的做法依然是先转成后缀表达式的形式,然后在进行计算。
  后缀表达式用vector<long> postfix的结构存储,为了方便,操作符和操作数都保存在postfix向量中,为了区分,操作数都以负数的形式存储,计算时在变成正数。
  

class Solution {public:    vector<long> convert2postfix(const string &s)    {        stack<char> op;        vector<long> postfix;        int tmp = 0,isPreNum = 0;        for(int i = 0; i < s.length(); i++)        {            switch(s[i])            {            case ' ':                continue;            case '*':            case '/':                while(!op.empty() && (op.top() == '*' || op.top() == '/'))                {                    postfix.push_back(op.top());                    op.pop();                }                op.push(s[i]);                break;            case '+':            case '-':                while(!op.empty())                {                    postfix.push_back(op.top());                    op.pop();                }                op.push(s[i]);                break;            default:                if(isPreNum)                    tmp = tmp*10 + s[i] - '0';                else                {                    tmp = s[i] - '0';                    isPreNum = 1;                }                if(i+1 ==s.length() || (i < s.length() && (s[i+1] >'9' || s[i+1] < '0')))                {                    postfix.push_back(-tmp);                     isPreNum = 0;                }            }        }         while(!op.empty())        {            postfix.push_back(op.top());            op.pop();        }        return postfix;    }    int calculate(string s) {        vector<long> postfix = convert2postfix(s);        if(postfix.size() == 0)            return 0;        stack<long> st;        long a,b;        for(int i = 0; i < postfix.size(); i++)        {            switch(postfix[i])            {            case '+':                a = st.top();st.pop();                b = st.top();st.pop();                st.push(b+a);                break;            case '-':                a = st.top();st.pop();                b = st.top();st.pop();                st.push(b-a);                break;            case '*':                a = st.top();st.pop();                b = st.top();st.pop();                st.push(b*a);                break;            case '/':                a = st.top();st.pop();                b = st.top();st.pop();                if(a == 0) return 0;                st.push(b/a);                break;            default:                st.push(-postfix[i]);            }        }        return st.top();    }};
0 0
原创粉丝点击