93. Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example: Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

public class Solution {

    List<String> res = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {

        restore(s, 0, new ArrayList<String>());
        return res;
    }


    private void restore(String s, int start,  List<String> list){
        if(list.size() == 4){
            if(start != s.length()) return;

            StringBuilder sb = new StringBuilder();
            for(String ss : list){
                sb.append(".");
                sb.append(ss);
            }
            sb.deleteCharAt(0);
            res.add(sb.toString());
            return;
        }

        for(int k = start+1; k<= s.length() && k <= start+4; k++){

            String q = s.substring(start, k);

            if(isValid(q)){
                list.add(q);
                restore(s, k, list);
                list.remove(list.size()-1);
            }
        }

    }

    private boolean isValid(String s){
        if(s.charAt(0) == '0') return s.equals("0");
        return Integer.parseInt(s) >=0 && Integer.parseInt(s) <= 255;
    }
}
public class Solution {
    List<String> res = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        if(s == null || s.length() < 4) return res;
        restore(s, new ArrayList<>());
        return res;
    }

    void restore(String s, List<String> list){
        if(list.size() == 4 ){
            if(s.length() != 0 ) return;
            StringBuilder sb = new StringBuilder();
            for(String t: list){
                sb.append('.').append(t);
            }
            sb.deleteCharAt(0);
            res.add(sb.toString());
            return;
        }

        int len = Math.min(4, s.length());
        for(int i=1; i<= len; i++){
            String p = s.substring(0, i);
            if(Integer.parseInt(p) > 255 || Integer.parseInt(p)< 0) break;
            if(p.charAt(0) == '0' && p.length() != 1) break;
            list.add(p);
            restore(s.substring(i), list);
            list.remove(list.size()-1);
        }
    }
}

results matching ""

    No results matching ""