- Convert Expression to Polish Notation
中文English
Given a string array representing an expression, and return the Polish notation of this expression. (remove the parentheses)
Example
Example 1:
Input: ["(", “5”, “-”, “6”, “)”, “", “7”]
Output: ["”, “-”, “5”, “6”, “7”]
Explanation: (5 - 6) * 7 = -1 * 7 = -7
* - 5 6 7 = * -1 7 = -7
Example 2:
Input: [“3”, “+”, “(”, “1”, “-”, “2”, “)”]
Output:["+", “3”, “-”, “1”, “2”]
Explanation: 3 + (1 - 2) = 3 + -1 = 2
+ 3 - 1 2 = + 3 -1 = 2
Clarification
Definition of Polish Notation:
http://en.wikipedia.org/wiki/Polish_notation
http://baike.baidu.com/view/7857952.htm
解法1:用stack
类似LIntCode370 逆波兰序列那题。不过是反过来读。最后把结果倒序即可。
代码如下:
class Solution {
public:
/**
* @param expression: A string array
* @return: The Polish notation of this expression
*/
vector<string> convertToPN(vector<string> &expression) {
int n = expression.size();
stack<string> st;
map<string, int> mp; //operator, priority
vector<string> result;
string topStr;
mp["+"] = 1;
mp["-"] = 1;
mp["*"] = 2;
mp["/"] = 2;
for (int i = n - 1; i >= 0; --i) {
string str = expression[i];
if (str.size() > 1 || isdigit(str[0]))
result.push_back(str);
else if (str == ")")
st.push(str);
else if (str == "(") {
while(st.top() != ")") {
topStr = st.top();
st.pop();
result.push_back(topStr);
}
st.pop();
} else { //+-*/
while(!st.empty() && (!isOperator(str) || mp[st.top()] > mp[str])) {
topStr = st.top();
st.pop();
result.push_back(topStr);
}
st.push(str);
}
}
while(!st.empty()) {
topStr = st.top();
st.pop();
result.push_back(topStr);
}
reverse(result.begin(), result.end());
return result;
}
private:
bool isOperator(string s) {
return (s.size() == 1 && !isdigit(s[0]));
}
};