问题描述:
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)
基本思想:
回溯法
代码:
//is 0 ok?
public boolean isValidIp(String s){
if(s.length() != 1 && s.startsWith("0"))
return false;
int ip = Integer.valueOf(s);
if(ip >= 0 && ip <=255)
return true;
return false;
}
public void validIp(List<String> list,String tmpIp,String allStr,int used,int i){
int size = allStr.length();
if(i == 5){
if(tmpIp.startsWith("."))
tmpIp = tmpIp.substring(1);
list.add(tmpIp);
}
if(allStr.length() - used > (4-i+1)*3 ||
allStr.length() -used < 4-i+1)
return;
int most,lest;
if(i == 4){
most = allStr.substring(used).length();
lest = most;
}
else{
most = 3;
lest = 1;
}
for(int j = lest; j<= most; j++){
if(j+used > size)
break;
String ip = allStr.substring(used,j+used);
boolean isIp = isValidIp(ip);
if(isIp){
tmpIp = tmpIp + "."+ip;
used = used + ip.length();
validIp(list,tmpIp,allStr,used,i+1);
tmpIp = tmpIp.substring(0,tmpIp.length()-ip.length()-1);
used = used-ip.length();
}
}
}
public List<String> restoreIpAddresses(String s) {
int size = s.length();
if(size < 4 || size >12)
return new ArrayList<String>();
List<String> result = new ArrayList<String>();
String tmpIp = "";
validIp(result,tmpIp,s,0,1);
return result;
}