Simple Recursion Based Java Solution


  • 0
    B
        public static List<String> restoreIpAddresses(String s){
            List<String> result = new ArrayList<>();
            restore(result, s, "", 0);
            return result;
        }
        public static void restore(List<String> result, String left, String accumulate, int index){
            if(index == 4){
                if(left.length() == 0) {
                    result.add(accumulate);
                    System.out.println(accumulate);
                }
            }
            else{
                for(int i=0;i<4;i++) {
                    if (left.length() >= i+1) {
                        String prefix = left.substring(0, i + 1);
                        String nleft = left.substring(i + 1);
                        if (Integer.parseInt(prefix) >= 0 && Integer.parseInt(prefix) <= 255 && prefix.equalsIgnoreCase(""+Integer.parseInt(prefix))) {
                            String naccumulate = "";
                            if (accumulate.isEmpty())
                                naccumulate = prefix;
                            else
                                naccumulate = accumulate + "." + prefix;
                            restore(result, nleft, naccumulate, index + 1);
                        }
                    }
                }
            }
        }
    

Log in to reply
 

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