这道题用的还是搜索,关键是临界条件很重要
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String>list = new ArrayList<>();
Set<String>set = new HashSet<>();
dfs(set,"",s,0,0);
return new ArrayList<>(set);
}
private void dfs(Set<String>set,String nowStr,String s,int index,int count){
int newcount = new Integer(count)+1;
//临界条件,我每次会在数字后面加一个点,最后会加四个点(最后一个点我是不要的),count来记录段数,有四段,每次计算一段 ,都会count+1
if (nowStr.length()-4==s.length()&&count==4){
set.add(nowStr.substring(0,nowStr.length()-1));
}
String newStr=new String(nowStr);
for (int i=3;i>=1;i--){
if (newcount==4){
newStr += s.substring(index, s.length());
String num = s.substring(index, s.length());
if(num.equals("")||num.length()>3)return;
int number = Integer.parseInt(s.substring(index, s.length()));
if (number >= 256) {
return;
}
if(num.charAt(0)=='0'&&num.length()!=1){
return;
}
}else {
if (index + i > s.length()) {
newStr = new String(nowStr);
continue;
}
newStr += s.substring(index, index + i);
String num = s.substring(index, index+i);
//特殊情况,位数不是一,开头又是0这是不行的,没有这种数,只有单独的0才行 if(num.charAt(0)=='0'&&num.length()!=1){
newStr = new String(nowStr);
continue;
}
int number = Integer.parseInt(num);
if (number >= 256) {
newStr = new String(nowStr);
continue;
}
}
newStr+='.';
dfs(set,newStr,s,index+i,newcount);
newStr = new String(nowStr);
}
}
}