题目:
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)
解决:
使用递归,每次截取满足条件的一段,最后一段还作判断是不是满足。
public class Solution {
ArrayList<String> lis = new ArrayList<String>();
public ArrayList<String> restoreIpAddresses(String s) {
if (s.length()<25)
ipHelper(s,0,0);
return lis;
}
public void ipHelper(String s,int pos,int num){
int len = s.length();
if (num==3){
if (pos < len){
String las = s.substring(pos);
if (len - pos >1){
if (las.startsWith("0")) return;
}
if (len - pos >3 || len - pos >1 && las.startsWith("0") || len - pos ==3 && Integer.parseInt(las)>255) return;
lis.add(s);
}
else
return;
}
num++;
if (len - pos >0){
String t = s.substring(0,pos+1)+"."+s.substring(pos+1);
ipHelper(t,pos+1+1,num);
if ("0".equals(s.substring(pos,pos+1))) return;
if (len -pos>1){
t = s.substring(0,pos+2)+"."+s.substring(pos+2);
ipHelper(t,pos+2+1,num);
}
if (len -pos>2){
t = s.substring(pos,pos+3);
if (Integer.parseInt(t)<256){
t = s.substring(0,pos+3)+"."+s.substring(pos+3);
ipHelper(t,pos+3+1,num);
}
}
}
}
}