Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created June 14, 2017 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/3fdcfbc84049a1a94deaae80dced35fb to your computer and use it in GitHub Desktop.
Save yokolet/3fdcfbc84049a1a94deaae80dced35fb to your computer and use it in GitHub Desktop.
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