Given a string containing only digits, restore it by returning allpossible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135","255.255.111.35"]
. (Order does not matter)
2014.8.9update:
出错的地方:
1.检查最后一个ip时,注意字符串开始为‘0’的情况:如果长度>1那么检测失败;否则为数字0,加入最后结果
2.检测非最后一个ip时,for (i = 0; i < s.length(); i++)注意S的长度可能小于3,所以要加上&&i
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<String>();
if (s.length() > 12) {
return result;
}
helper(result, s, "", 0);
return result;
}
void helper(List<String> result, String s, String last, int pos) {
if (pos == 4 && s.isEmpty()) {
result.add(last);
return;
} else if (s.isEmpty()) {
return;
} else if (s.charAt(0) == '0') {
helper(result, s.substring(1), last + (pos == 0 ? "0" : ".0"), pos+1);
return;
}
for (int i = 0; i < 3 && i < s.length(); i++) {
String str = s.substring(0, i+1);
if (Integer.valueOf(str) < 256) {
String tmp = last + (pos == 0 ? "" : ".") + str;
helper(result, s.substring(i+1), tmp, pos+1);
}
}
}