LeetCode 93 Restore IP Addresses
Description
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)
Solution
- 问题是要把一段字符串转换成可能的ip地址
- 定义返回变量solutions
- 传入restoreIp函数中
- restoreIp 函数有四个参数原始的ip字符串、 返回结果solutions、idx(当前ip的索引)、restored、count(用来记录切割的ip段, ip总共四段)
- count > 4 就返回
- count == 4 && idx == ip的长度,意味着完成了ip地址的转换,并将存储的变量restored 加入到 solutions中
- 进行for循环 i = 1 2 3
如果idx+i > ip.length() 跳出循环
s = ip.substring(idx, idx+i)
s以0开始而且长度大于1 || i = 3&&s>256 跳过下一条语句
递归调用restoreIp(ip, solutions, idx移动i, restored + s + (count == 3 ? "" : "."), count +1);
Code
public class Solution {
public List restoreIpAddresses(String s) {
List solutions = new ArrayList<>();
restoreIp(s, solutions, 0, "", 0);
return solutions;
}
private void restoreIp(String ip, List solutions, int idx, String restored, int count) {
if(count > 4) return;
if(count == 4 && idx == ip.length()) {
solutions.add(restored);
}
for(int i = 1; i < 4; i++) {
if(idx + i > ip.length()) break;
String s = ip.substring(idx, idx+i);
if ((s.startsWith("0") && s.length() > 1) || (i == 3 && Integer.parseInt(s) >= 256))
continue;
restoreIp(ip, solutions, idx+i, restored+s+(count == 3 ? "" : "."), count+1);
}
}
}