LINTCODE——将表达式转换为逆波兰表达式
思路:有了表达式求值的基础(请点击):
题目就是中缀表达式转换为后缀表达式;
class Solution {
public:
/*
* @param expression: A string array
* @return: The Reverse Polish notation of this expression
*/
vector<string> convertToRPN(vector<string> &expression) {
// write your code here
vector<string> res;
res = endE(expression);
return res;
}
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();
}
}
}
}
while(!s.empty())
{
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;
}
}
};