Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
public class Solution {
public static void main(String[] args) {
String s = "1271458";
ArrayList<String> list = (new Solution()).restoreIpAddresses(s);
System.out.println(list);
}
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> list = new ArrayList<String>();
if (s == null || s.length() > 12 || s.length() < 4) return list;
restore(s, 1, "", list);
return list;
}
public void restore(String s, int num, String ip, ArrayList<String> list) {
if (s == null || s.length() == 0) return;
if (num == 4 && valid(s)) {
ip += s;
list.add(ip);
return;
}
for (int i = 1; i <= 3; i++) {
if (i > s.length()) break;
String pre = s.substring(0, i);
if (valid(pre)) {
String post = s.substring(i);
restore(post, num + 1, ip + pre + ".", list);
}
}
}
public boolean valid(String s) {
if (s == null || s.length() == 0) return false;
if (s.length() > 1 && s.charAt(0) == '0') return false;
int v = Integer.parseInt(s);
if (v >= 0 && v <= 255) return true;
return false;
}
}