需要注意:
- 1.每一段不能超过255,也就是长度不可能超过4
- 2.如果某段以0开头,那么这一段只能是0,比如0.0.0.1这种
- 3.所以整个过程需要的元素有
- 当前在凑的是第几段
- 存结果的list
- 之前凑的那些的字符串
- 当前这段从哪个下标开始
知道这些就可以写代码了,不外乎就是DFS,然后过程擦除
public ArrayList<String> restoreIpAddresses (String s) {
ArrayList<String> res = new ArrayList<>();
if(s!=null&&s.length()>0){
process(res,s.toCharArray(),0,1,new StringBuilder());
}
return res;
}
public void process(ArrayList<String> res,char[] strChars,int start,
int curPart,StringBuilder builder){
int N = strChars.length;
if(start==N){
if(curPart==5){
builder.deleteCharAt(builder.length()-1);
res.add(builder.toString());
builder.append('.');
}
return;
}
if(curPart>4) return;
//枚举当前片段,最长为三,0只能单个一段
if(strChars[start]=='0'){
builder.append('0').append('.');
process(res,strChars,start+1,curPart+1,builder);
builder.delete(builder.length()-2,builder.length());
}else{
//当前片段枚举长度
int partNum = 0;
int curLen = builder.length();
int end;
for(int i = 0;i<3&&(end = start+i)<N;i++){
partNum = partNum*10+(strChars[end]-'0');
if(partNum<=255){
builder.append(partNum).append(".");
process(res,strChars,end+1,curPart+1,builder);
builder.delete(curLen,builder.length());
}
}
}
}