Simple Java


  • 0
    C
    public static final int[] VALID_NUM = new int[]{12, 9, 6, 3};
    
        public List<String> restoreIpAddresses(String s) {
            List<String> res = new ArrayList<>();
            if (s == null || s.length() < 4 || s.length() > 12) {
                return res;
            }
    
            backTracking(s, res, new StringBuilder(), 0);
            
            return res;
        }
    
        public void backTracking(String s, List<String> res, StringBuilder sb, int digit) {
            if (digit >= 4 || s.length() > VALID_NUM[digit] || s.length() < 4 - digit) {
                return;
            }
            if (digit == 3) {
                int valueOfStr = Integer.valueOf(s);
    
                if (s.length() > 1 && s.charAt(0) == '0') {
                    return;
                }
                if (valueOfStr > 255) {
                    return;
                }
                sb.append(".").append(s);
                res.add(sb.toString());
                return;
            }
            int length = sb.length();
            for(int i = 0; i < 4; i ++) {
                if(i+1 > s.length()) return;
                int valueOfSubString = Integer.valueOf(s.substring(0, i + 1));
                if (valueOfSubString > 255 || (i != 0 && s.charAt(0) == '0')) {
                    return;
                }
                if (digit == 0) {
                    sb.append(valueOfSubString);
                } else {
                    sb.append(".").append(valueOfSubString);
                }
                backTracking(s.substring(i + 1), res, sb, digit + 1);
                sb.setLength(length);
            }
        }
    }
    

Log in to reply
 

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