Advertisement
1988coder

93. Restore IP Addresses

Dec 31st, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. /**
  2.  * Time Complexity : O(3^3 * N) = O(N)
  3.  *
  4.  * For every i, j runs thrice. For every j, k runs thrice. Thus for every i, k
  5.  * runs 3*3 times. Since i runs thrice too, all for loops will run for 3*3*3
  6.  * times.
  7.  *
  8.  * Space Complexity: O(N) .. This is required for Substring
  9.  *
  10.  * N = Length of the input string
  11.  */
  12. class Solution {
  13.     public List<String> restoreIpAddresses(String s) {
  14.         List<String> result = new ArrayList();
  15.         if (s == null || s.length() < 4 || s.length() > 12) {
  16.             return result;
  17.         }
  18.  
  19.         int strLen = s.length();
  20.  
  21.         for (int i = 1; i < 4 && i < strLen - 2; i++) {
  22.             for (int j = i + 1; j < i + 4 && j < strLen - 1; j++) {
  23.                 for (int k = j + 1; k < j + 4 && k < strLen; k++) {
  24.                     String octet1 = s.substring(0, i);
  25.                     String octet2 = s.substring(i, j);
  26.                     String octet3 = s.substring(j, k);
  27.                     String octet4 = s.substring(k, strLen);
  28.                     if (isValidOctet(octet1) && isValidOctet(octet2) && isValidOctet(octet3) && isValidOctet(octet4)) {
  29.                         result.add(octet1 + "." + octet2 + "." + octet3 + "." + octet4);
  30.                     }
  31.                 }
  32.             }
  33.         }
  34.         return result;
  35.     }
  36.  
  37.     private boolean isValidOctet(String o) {
  38.         if (o.length() == 0 || o.length() > 3 || (o.length() > 1 && o.charAt(0) == '0') || Integer.parseInt(o) > 255) {
  39.             return false;
  40.         }
  41.         return true;
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement