1.题目
给一个由数字组成的字符串。求出其可能恢复为的所有IP地址。
给出字符串 "25525511135"
,所有可能的IP地址为:
[
"255.255.11.135",
"255.255.111.35"
]
(顺序无关紧要)
2.算法
基本思路就是取出一个合法的数字,作为IP地址的一项,然后递归处理剩下的项。
public ArrayList<String> restoreIpAddresses(String s)
{
// Write your code here
ArrayList<String> res = new ArrayList<String>();
if (s == null)
{
return res;
}
helper(s, 0, 1, "", res);
return res;
}
public void helper(String s, int index, int segment, String item, ArrayList<String> res)
{
if (index >= s.length())
{
return;
}
if (segment == 4)
{
String str = s.substring(index);
if (isValid(str))
{
res.add(item + "." + str);
}
return;
}
for (int i = 1; i < 4 && (i + index <= s.length()); i++)
{
String str = s.substring(index, index + i);
if (isValid(str))
{
if (segment == 1)
{
helper(s, index + i, segment + 1, str, res);
}
else
{
helper(s, index + i, segment + 1,item + "."+ str, res);
}
}
}
}
public boolean isValid(String str)
{
if (str == null || str.length() > 3)
{
return false;
}
int num = Integer.parseInt(str);
if (str.charAt(0) == '0' && str.length() > 1)
{
return false;
}
if (num >= 0 && num <= 255)
{
return true;
}
return false;
}