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)
Java:
1. 征服代码:http://blog.csdn.net/linhuanmars/article/details/24683699
public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> res = new ArrayList<String>();
if(s==null||s.length()==0) return res;
help(s,0,1,"",res);
return res;
}
private void help(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)
{
help(s,index+i,segment+1,str,res);
}
else
{
help(s,index+i,segment+1,item+"."+str,res);
}
}
}
}
private 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;
return num>=0&&num<=255;
}
}
2. 第二种解法 类似于对征服代码的解释,http://blog.csdn.net/u011095253/article/details/9158449
public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> res = new ArrayList<String>();
if (s.length()<4||s.length()>12) return res;
dfs(s,"",res,0);
return res;
}
public void dfs(String s, String tmp, ArrayList<String> res, int count){
if (count == 3 && isValid(s)) {
res.add(tmp + s);
return;
}
for(int i=1; i<4 && i<s.length(); i++){
String substr = s.substring(0,i);
if (isValid(substr)){
dfs(s.substring(i), tmp + substr + '.', res, count+1);
}
}
}
public boolean isValid(String s){
if (s.charAt(0)=='0') return s.equals("0");
int num = Integer.parseInt(s);
return num<=255 && num>0;
}
}