flag用于防止重复入栈,将运算符设置优先级,并且区别右括号匹配做括号这一特殊情况。
#include <vector>
#include <stack>
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
int n=expression.size();
vector<string> a;
stack<string> c;
for(int it=0;it<n;it++){
if(cmp(expression[it])==0)
a.push_back(expression[it]);
else if(expression[it]==")"){
while(c.top()!="("){
a.push_back(c.top());
c.pop();
}
c.pop();
}
else
{
bool flag=true;
while(flag){
if(c.empty() || expression[it] == "(" || c.top() == "(" || (cmp(expression[it]) > cmp(c.top())) ){
c.push(expression[it]);
flag=false;
}
else
{
a.push_back(c.top());
c.pop();
}
}
}
}
while(!c.empty()){
a.push_back(c.top());
c.pop();
}
return a;
}
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;
}
}
};