1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class Solution { public List<Integer> diffWaysToCompute(String input) { if (input.equals("")) return new LinkedList<Integer>(); String operand = ""; List<Integer> result = new LinkedList<Integer>(); for (int i = 0; i < input.length(); i++){ if (!Character.isDigit(input.charAt(i))){ List<Integer> rightSide = diffWaysToCompute(input.substring(i+1)); List<Integer> leftSide = diffWaysToCompute(input.substring(0, i)); char operator = input.charAt(i); for (Integer left:leftSide){ for (Integer right:rightSide){ result.add(eval(operator, left, right)); } } }else{ operand+=input.charAt(i); } } if (result.size() == 0) result.add(Integer.valueOf(operand)); return result; } int eval(char operator, int operand1, int operand2){ if (operator == '*') return operand1*operand2; else if (operator == '+') return operand1+operand2; return operand1-operand2; } } |
Wednesday, December 23, 2015
[leetcode]Different Ways to add parentheses
divide and conquer, 总是分成两半...
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment