straight but slow and long


  • 0
    F
        public List<String> restoreIpAddresses(String s) {
            Objects.requireNonNull(s);
            ArrayList<String> result = new ArrayList<>();
            int n = s.length();
            if (n < 4 || n > 12) {
                return result;
            }
            for (int i = 1; i <= Math.min(3, n - 3); i++) {
                for (int j = i + 1; j <= Math.min(i + 3, n - 2); j++) {
                    for (int k = j + 1; k <= Math.min(j + 3, n - 1); k++) {
                        String a = s.substring(0, i);
                        String b = s.substring(i, j);
                        String c = s.substring(j, k);
                        String d = s.substring(k);
                        if (d.length() <= 3 && validate(a) && validate(b) && validate(c) && validate(d)) {
                            result.add(String.format("%s.%s.%s.%s", a, b, c, d));
                        }
                    }
                }
            }
            return result;
        }
    
        private boolean validate(String s) {
            Objects.requireNonNull(s);
            int n = s.length();
            if (n == 1) {
                return s.compareTo("0") >= 0 && s.compareTo("9") <= 0;
            } else if (n == 2) {
                return s.compareTo("10") >= 0 && s.compareTo("99") <= 0;
            } else {
                return n == 3 && s.compareTo("100") >= 0 && s.compareTo("255") <= 0;
            }
        }

Log in to reply
 

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