The basic idea is using a stack to store every operator.
For parentheses, if we meet “)” we add it into stack. if we meet”(” we pop stack till we meet “)”.
class Solution {
public:
/**
* @param expression: A string array
* @return: The Polish notation of this expression
*/
vector<string> convertToPN(vector<string> &expression) {
// write your code here
vector<string> res;
stack<string> stk;
for (int i = expression.size()-1; i>=0; --i) {
string cur = expression[i];
if(isOperator(cur)){
if(cur == ")"){
stk.push(cur);
}else if(cur == "("){
while(!stk.empty()){
string tmpOp = stk.top();
stk.pop();
if (tmpOp == ")") break;
res.push_back(tmpOp);
}
}else{
while(!stk.empty() && order(cur) < order(stk.top())){
res.push_back(stk.top());
stk.pop();
}
stk.push(cur);
}
}else res.push_back(cur);
}
while(!stk.empty()) {
res.push_back(stk.top());
stk.pop();
}
reverse(res.begin(), res.end());
return res;
}
bool isOperator(string s){
if(s == "+" || s == "*" || s == "/" || s == "-" || s=="(" || s==")") return true;
else return false;
}
int order(string s){
if(s == "*" || s=="/") return 2;
else if(s=="+" || s=="-") return 1;
else return 0;
}
};
The code has O(n) time complexity with O(n) memory.