Easy understanding java solution


  • 0
    public List<String> restoreIpAddresses(String s) {
        List<String> list = new ArrayList<>();
        if(s == null || s.length() < 4) return list;
        search(s, 0, 0, new StringBuilder(), list);
        return list;
    }
    
    public void search(String s, int index, int count, StringBuilder sb, List<String> list) {
        if(count == 4) {
            if(index == s.length()) list.add(sb.toString());
            return;
        }
        
        for(int i=1; i+index<=s.length() && i <= 3; i++) {
            int num = Integer.parseInt(s.substring(index, index+i));
            if(num >= 0 && num <= 255) {
                if(num < 10 && i > 1) return;
                StringBuilder newSb = new StringBuilder(sb);
                if(count == 0) newSb.append(num);
                else newSb.append(".").append(num);
                search(s, index+i, count+1, newSb, list);
            } else {
                return;
            }
        }
    }

Log in to reply
 

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