1. 问题描述
给遗传字符串类型的表达式,计算表达式的值。表达式只包含+、-、*、/和空格。
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();
}
};