public List<String> restoreIpAddresses(String s) {
List<String> list = new LinkedList<>();
dfs(s, s.length(), 0, 4, new StringBuilder(),list);
return list;
}
/**
* dfs 深度优先搜索
*
* @param str
* @param index
* @param length
* @param path
*/
public static void dfs(String str, int length, int index, int remain, StringBuilder path, List<String> res) {
if (remain == 0 && index == length) {
res.add(path.toString());
return;
}
if (remain < 0 || index == length) {
return;
}
for (int i = index + 1; i <= index + 3; i++) {
if (i > length) {
break;
}
String temp = str.substring(index, i);
if (isRight(temp)) {
path.append(temp);
if (remain > 1) {
path.append(".");
}
//深度优先遍历
dfs(str, length, i, remain - 1, path, res);
if (remain > 1) {
path.deleteCharAt(path.length() - 1);
}
path.delete(path.length() - temp.length(), path.length());
}
}
}
/**
* 字符串是否是合法的
*
* @param s
* @return
*/
public static boolean isRight(String s) {
int length = s.length();
int value = Integer.valueOf(s);
return length == 1 || length == 2 && (10 <= value) && (value <= 99) || length == 3 && (100 <= value) && (value <= 255);
}