http://www.lintcode.com/en/problem/convert-expression-to-reverse-polish-notation/
中綴表達式轉成後綴表達式
For the expression [3
- 4 + 5]
(which denote by ["3", "-", "4", "+", "5"]), return [3
4 - 5 +]
(which denote by ["3", "4", "-", "5", "+"])
中綴表達式a + b*c + (d * e + f) * g,其轉換成後綴表達式則爲a b c * + d e * f + g * +。
轉換過程需要用到棧,具體過程如下:
1)如果遇到操作數,我們就直接將其輸出。
2)如果遇到操作符,則我們將其放入到棧中,遇到左括號時我們也將其放入棧中。
3)如果遇到一個右括號,則將棧元素彈出,將彈出的操作符輸出直到遇到左括號爲止。注意,左括號只彈出並不輸出。
4)如果遇到任何其他的操作符,如(“+”, “*”,“(”)等,從棧中彈出元素直到遇到發現更低優先級的元素(或者棧爲空)爲止。彈出完這些元素後,纔將遇到的操作符壓入到棧中。有一點需要注意,只有在遇到" ) "的情況下我們才彈出" ( ",其他情況我們都不會彈出" ( "。
5)如果我們讀到了輸入的末尾,則將棧中所有元素依次彈出。
public class Solution {
/**
* @param expression: A string array
* @return: The Reverse Polish notation of this expression
*/
public ArrayList<String> convertToRPN(String[] expression) {
// write your code here
ArrayList<String> res = new ArrayList();
Stack<String> stack = new Stack();
HashMap<String, Integer> map = new HashMap();
// 優先級越高值越大
map.put("+", 1);
map.put("-", 1);
map.put("*", 2);
map.put("/", 2);
map.put("(", 3);
for (String s : expression) {
if (Character.isDigit(s.charAt(0))) {
res.add(s);
} else {
if (s.equals(")")) {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
res.add(stack.pop());
}
if (!stack.isEmpty()) {
stack.pop();
}
} else {
while (!stack.isEmpty() && map.get(s) <= map.get(stack.peek())) {
// “(”只有遇到右括號纔出棧,否則break
if (stack.peek().equals("(")) {
break;
}
res.add(stack.pop());
}
stack.push(s);
}
}
}
while (!stack.isEmpty()) {
res.add(stack.pop());
}
return res;
}
}