public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
backTrack(res, s, "", 0, 0);
return res;
}
private void backTrack(List<String> res, String ip, String tmp, int idx, int cnt) {
if (cnt == 4) {
if (idx == ip.length()) res.add(tmp);
return;
}
for (int i = 1; i <= 3; i++) {
if (idx + i > ip.length()) continue;
String s = ip.substring(idx, idx+i);
if ((s.startsWith("0") && s.length() > 1) || (Integer.valueOf(s) > 255)) continue;
if (cnt == 3) {
backTrack(res, ip, tmp + s, idx + i, cnt + 1);
}
else {
backTrack(res, ip, tmp + s + ".", idx + i, cnt + 1);
}
}
}
93. 复原IP地址
最新推荐文章于 2024-03-07 12:21:29 发布