369 · Convert Expression to Polish Notation
Algorithms
Medium
Description
Given a string array representing an expression, and return the Polish notation of this expression. (remove the parentheses)
Wechat reply 【Google】 get the latest requent Interview questions. (wechat id : jiuzhang0607)
Definition of Polish Notation:
http://en.wikipedia.org/wiki/Polish_notation
http://baike.baidu.com/view/7857952.htm
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
Tags
Related Problems
368
Expression Evaluation
Hard
370
Convert Expression to Reverse Polish Notation
Medium
424
Evaluate Reverse Polish Notation
Medium
1908
Boolean expression evaluation
Hard
解法1:
这题可以用stack来解决,方法跟LintCode 370一样,不过这里因为波兰表达式是前序,我们要从后往前遍历expression数组,对于expression[i],
- 如果是")"就压栈,
- 如果是"(“就挨个弹栈,把栈顶元素写到res,直到遇到”(",
- 如果是数字就直接写到res,
- 如果是操作符,那就跟栈顶元素比较,注意不管是波兰还是逆波兰,这里都是不允许优先级小的操作符压在操作符大的操作符上面的,所以如果栈顶元素比这个expression[i]的优先级大就把弹栈,把栈顶元素写到res,直到栈顶元素优先级不大于expression[i]。
- 注意:如果栈顶元素跟expression[i]的优先级一样大呢?这里跟逆波兰不一样!因为逆波兰是从前往后遍历expression,所以栈顶元素跟expression[i]一样大的话,栈顶元素也是应该在expression[i]之前的,所以我们要用
while (!optrStk.empty() && prio[optrStk.top()] >= prio[exprStr])
而波兰表达式这里是从后往前遍历expression,优先级一样的话,栈顶元素应该排在expression[i]之后,所以我们要用
while (!optrStk.empty() && prio[optrStk.top()] > prio[exprStr])
class Solution {
public:
/**
* @param expression: A string array
* @return: The Polish notation of this expression
*/
vector<string> convertToPN(vector<string> &expression) {
int len = expression.size();
stack<string> optrStk;
vector<string> res;
map<string, int> prio;
prio["+"] = 1;
prio["-"] = 1;
prio["*"] = 2;
prio["/"] = 2;
for (int i = len - 1; i >= 0; i--) {
string exprStr = expression[i];
if (exprStr.size() > 1 || (exprStr[0] >= '0' && exprStr[0] <= '9')) {
res.push_back(exprStr);
continue;
}
if (exprStr == ")") {
optrStk.push(exprStr);
continue;
}
if (exprStr == "(") {
while (!optrStk.empty() && optrStk.top() != ")") {
res.push_back(optrStk.top());
optrStk.pop();
}
optrStk.pop(); //pop the ")"
continue;
}
//while (!optrStk.empty() && prio[optrStk.top()] >= prio[exprStr]) {
while (!optrStk.empty() && prio[optrStk.top()] > prio[exprStr]) {
res.push_back(optrStk.top());
optrStk.pop();
}
optrStk.push(exprStr);
}
//dump the rest in optrStrk to res
while (!optrStk.empty()) {
res.push_back(optrStk.top());
optrStk.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
解法2:这题应该也可以递归来做。先找到优先级最低的元素打印出来,然后左右两边分别递归,把结果分别累加到结果后面。下次再做。