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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public List<Integer> diffWaysToCompute(String input) { return diffWaysToCompute(input, 0, input.length()); }
public List<Integer> diffWaysToCompute(String input, int startIndex, int endIndex){ boolean isDigit = true; List<Integer> result = new ArrayList<Integer>(); for(int i = startIndex ; i<endIndex ; i++){ char cur = input.charAt(i); if(cur == '+' || cur == '-' || cur=='*' ){ isDigit = false; List<Integer> leftValue = diffWaysToCompute(input, startIndex, i); List<Integer> rightValue = diffWaysToCompute(input, i+1, endIndex); result.addAll(compute(leftValue, rightValue,cur)); } } if(isDigit){ result.add(Integer.parseInt(input.substring(startIndex, endIndex))); } return result; }
public List<Integer> compute(List<Integer> leftValue, List<Integer> rightValue, char operator){ switch(operator){ case '+' : return add(leftValue, rightValue); case '-' : return minus(leftValue, rightValue); case '*' : return multiply(leftValue, rightValue); } return new ArrayList<>(); }
public List<Integer> add(List<Integer> leftValue, List<Integer> rightValue){ List<Integer> result = new ArrayList<Integer>(); for(int left : leftValue){ for(int right : rightValue){ result.add(left + right); } } return result; }
public List<Integer> minus(List<Integer> leftValue, List<Integer> rightValue){ List<Integer> result = new ArrayList<Integer>(); for(int left : leftValue){ for(int right : rightValue){ result.add(left - right); } } return result; }
public List<Integer> multiply(List<Integer> leftValue, List<Integer> rightValue){ List<Integer> result = new ArrayList<Integer>(); for(int left : leftValue){ for(int right : rightValue){ result.add(left * right); } } return result; }
|