LINTCODE——表达式求值
前期准备:
首先我们得要了解前缀、中缀、后缀表示式分别是什么,然后计算方法是什么
举例:
(3 + 4) × 5 - 6 就是中缀表达式
- × + 3 4 5 6 前缀表达式
3 4 + 5 × 6 - 后缀表达式
说简单点就是运算符的位置,在前的话就是前缀,以此类推;
详细了解请点击:
对于计算机来说,中缀表达式是相当复杂的,所以我们为了他简化问题,那么就可以理解为,这套题目考的就是由中缀表达式转换成前缀或者后缀表达式求值,话不多说,直接上代码。
我把中缀转前缀和后缀的代码都写了,不过最后计算使用前缀表达式计算的,感兴趣的自己算后缀表达式的值;
class Solution {
public:
/*
* @param expression: a list of strings
* @return: an integer
*/
int evaluateExpression(vector<string> &expression) {
// write your code here
//将中缀变为前缀;
vector<string> sbegin,send;
sbegin = beginE(expression);
//将中缀变为后缀
send = endE(expression);
//计算前缀表达式
stack<int> res;
for(auto x : sbegin)
{
if(cmp(x) == 0)
res.push(stoi(x));
else
{
int temp1 = res.top();
res.pop();
int temp2 = res.top();
res.pop();
int temp = acl(temp1,x,temp2);
res.push(temp);
}
}
return res.empty()? 0 : res.top();
}
vector<string> beginE(vector<string> &stemp)
{
stack<string> s;
vector<string> sbegin;
int n = stemp.size();
for(int i = n-1; i >= 0; i--)
{
if(cmp(stemp[i]) == 0)
sbegin.push_back(stemp[i]);
else if(stemp[i] == "(")
{
//将s压入sbegin
while(s.top() != ")")
{
sbegin.push_back(s.top());
s.pop();
}
s.pop();
}
else
{
bool flag = true;
while(flag){
if(s.empty() || stemp[i] == ")" || s.top() == ")" || (cmp(stemp[i]) >= cmp(s.top())) )
{
s.push(stemp[i]);
flag = false;
}
else
{
sbegin.push_back(s.top());
s.pop();
}
}
}
}
while(!s.empty())
{
sbegin.push_back(s.top());
s.pop();
}
return sbegin;
}
vector<string> endE(vector<string> &stemp)
{
stack<string> s;
vector<string> send;
int n = stemp.size();
for(int i = 0; i < n; i++)
{
if(cmp(stemp[i]) == 0)
send.push_back(stemp[i]);
else if(stemp[i] == ")")
{
//将s压入sbegin
while(s.top() != "(")
{
send.push_back(s.top());
s.pop();
}
s.pop();
}
else
{
bool flag = true;
while(flag){
if(s.empty() || stemp[i] == "(" || s.top() == "(" || (cmp(stemp[i]) > cmp(s.top())) )
{
s.push(stemp[i]);
flag = false;
}
else
{
send.push_back(s.top());
s.pop();
}
}
}
}
return send;
}
int cmp(string a)
{
switch (a[0]){
case '+' :
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '(':
return 3;
case ')':
return 3;
default:
return 0;
}
}
int acl(int a , string x, int b)
{
switch (x[0]){
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
default:
return 0;
}
}
};