題目
https://leetcode.com/problems/expression-add-operators/description/
題解
中綴表達式求值問題,參考:leetcode 227. Basic Calculator II | 227. 基本計算器 II(中綴表達式求值)
本題主要是兩個回溯,第一個回溯用來切割數字,第二個回溯用來插入運算符。以上兩項工作做完后,用經典的中綴表達式求值,計算是否為 target 即可。
class Solution {int N;List<String> result
;HashMap<String, Integer> priorityMap
; String[] ops
;public void initPriorityMap() {priorityMap
= new HashMap<>();priorityMap
.put("+", 0);priorityMap
.put("-", 0);priorityMap
.put("*", 1);}public List<String> addOperators(String num
, int target
) {N = num
.length();result
= new ArrayList<>();ops
= new String[]{"+", "-", "*"};initPriorityMap();splitNums(num
, 0, target
, new LinkedList<>());return result
;}public void splitNums(String num
, int i
, int target
, Deque<Integer> queue
) { if (i
== N) {genExp(queue
, target
, new LinkedList<>());}for (int j
= i
+ 1; j
<= N; j
++) {String sub
= num
.substring(i
, j
);if (sub
.startsWith("0") && sub
.length() > 1 || Long.parseLong(sub
) > Integer.MAX_VALUE
) continue;queue
.add(Integer.valueOf(sub
)); splitNums(num
, j
, target
, queue
);queue
.removeLast();}}public void genExp(Deque<Integer> queue
, int target
, Deque<String> exp
) { Deque<Integer> q
= new LinkedList<>(queue
);if (q
.size() == 1) {exp
.add(String.valueOf(q
.pollFirst()));
Integer res
= calExpression(exp
, target
);if (res
== target
) {StringBuilder sb
= new StringBuilder();for (String s
: exp
) {sb
.append(s
);}result
.add(sb
.toString());}exp
.pollLast();return;}exp
.add(String.valueOf(q
.pollFirst()));for (String op
: ops
) {exp
.add(op
);genExp(q
, target
, exp
);exp
.pollLast();}exp
.pollLast();}public Integer calExpression(Deque<String> exp
, int target
) { Stack<Integer> s1
= new Stack<>(); Stack<String> s2
= new Stack<>(); boolean isNum
= false;Deque<String> q
= new LinkedList<>(exp
);while (!q
.isEmpty()) {isNum
= !isNum
;String val
= q
.pollFirst();if (isNum
) { s1
.push(Integer.valueOf(val
));} else { if (s2
.isEmpty() || isPrior(val
, s2
.peek())) { s2
.push(val
);} else { while (s2
.size() > 0 && !isPrior(val
, s2
.peek())) {String op
= s2
.pop();Integer n1
= s1
.pop();Integer n2
= s1
.pop();int res
= cal(n1
, n2
, op
);s1
.push(res
);}s2
.push(val
);}}}while (!s2
.isEmpty()) { String op
= s2
.pop();Integer n1
= s1
.pop();Integer n2
= s1
.pop();int res
= cal(n1
, n2
, op
);s1
.push(res
);}return s1
.pop();}public int cal(int n1
, int n2
, String op
) {switch (op
) {case "+":return n2
+ n1
;case "-":return n2
- n1
;case "*":return n2
* n1
;default:System.out
.println("op err");return -1;}}public boolean isPrior(String op1
, String op2
) {return priorityMap
.get(op1
) > priorityMap
.get(op2
);}
}
總結
以上是生活随笔為你收集整理的leetcode 282. Expression Add Operators | 282. 给表达式添加运算符(中缀表达式求值)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。