8 ms Java Divide and Conquer


  • 0
    public class Solution {
        public List<Integer> diffWaysToCompute(String input) {
            List<Integer> res = new ArrayList<>();
            if (input == null || input.length() == 0) {
                return res;
            }
            boolean hasSymbol = false;
            for (int i = 0; i < input.length(); i++) {
                char symbol = input.charAt(i);
                if (!isSymbol(symbol)) {
                    continue;
                }
                hasSymbol = true;
                List<Integer> left = diffWaysToCompute(input.substring(0, i));
                List<Integer> right = diffWaysToCompute(input.substring(i + 1));
                combine(left, right, res, symbol);
            }
            if (!hasSymbol) {
                res.add(Integer.valueOf(input));
            }
            return res;
        }
        
        public void combine(List<Integer> left, List<Integer> right, List<Integer> res, char symbol) {
            for (Integer leftInt : left) {
                for (Integer rightInt : right) {
                    if (symbol == '+') {
                        res.add(leftInt + rightInt);
                    } else if (symbol == '-') {
                        res.add(leftInt - rightInt);
                    } else {
                        res.add(leftInt * rightInt);
                    }
                }
            }
        }
        
        // +, - and *
        public boolean isSymbol(char a) {
            if (a == '+' || a== '-' || a == '*') {
                return true;
            }
            return false;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.