您的位置:首页 > 其它

《leetCode》:Restore IP Addresses

2015-12-27 18:50 344 查看

题目

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)


思路

the basic idea is to make three cuts into the string, separating it into four parts, each part contains 1~3 digits and it must be <=255.

实现代码如下:

public class Solution {
/*
* the basic idea is to make three cuts into the string,
* separating it into four parts, each part contains 1~3 digits and it must be <255.
* */
public List<String> restoreIpAddresses(String s) {
List<String> result=new ArrayList<String>();
if(s.length()<4){
return result;
}

int len=s.length();
for(int i=1;i<=3;i++){//切第一刀
if(len-i>9) continue;
for(int j=i+1;j<=i+3;j++){
if(len-j>6) continue;
for(int k=j+1;k<=j+3&&k<len;k++){
if(len-k>3) continue;
//看看此时切出来的几个部分是否满足数字<=255,如果满足条件
int a,b,c,d;
a=Integer.parseInt(s.substring(0,i));
b=Integer.parseInt(s.substring(i, j));
c=Integer.parseInt(s.substring(j, k));
d=Integer.parseInt(s.substring(k, len));
if(a>255||b>255||c>255||d>255) continue;
String res=a+"."+b+"."+c+"."+d;
if(res.length()<len+3) continue;//不允许出现这样的情况:"01"----->1;例如s="10000"时,只能有10.0.0.0这个结果
result.add(res);

}
}
}
return  result;

}
}


小结

此题目我并没有想出来这么做,是看的网上的。

一般采用的方法是采用回溯法来做,但是不怎么好理解,这个方法是我见到最好理解并且很好的方法。

参考地址://https://leetcode.com/discuss/19296/my-concise-ac-java-code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: