Created
June 14, 2017 02:44
-
-
Save yokolet/3fdcfbc84049a1a94deaae80dced35fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
public class RestoreIpAddresses { | |
static void restoreIpAddresses(String s, List<String> result, String ip, int count, int index) { | |
if (count > 4) { return; } | |
if (count == 4 && ip.length() == (s.length() + 3)) { | |
result.add(ip); | |
} | |
for (int i = 1; i <= 3; i++) { | |
if (index + i > s.length()) { break; } | |
String sub = s.substring(index, index + i); | |
if ((sub.charAt(0) == '0' && i > 1) || (Integer.parseInt(sub) > 255 && i == 3)) { | |
continue; | |
} | |
String next = ip + sub + (count == 3 ? "" : "."); | |
restoreIpAddresses(s, result, next, count + 1, index + i); | |
} | |
} | |
static List<String> restoreIpAddresses(String s) { | |
List<String> result = new ArrayList(); | |
if (s.isEmpty()) { return result; } | |
restoreIpAddresses(s, result, "", 0, 0); | |
return result; | |
} | |
public static void main(String[] args) { | |
String s; | |
s = "25525511135"; | |
System.out.println(restoreIpAddresses(s)); | |
s = "0000"; | |
System.out.println(restoreIpAddresses(s)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment