您的位置:首页 > 其它

LeetCode 59 Restore IP Addresses

2014-08-31 22:35 405 查看
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).

分析:

IP地址由四部分组成,每一部分从0到255之间的数字,因此是1到3位都有可能。

从第一部分开始,尝试1位到3位,接着第二部分,第三部分,最后剩下的是第四部分。只有当前部分合格,才进入下一部分的检验,知道最后,把合格的IP地址部分中间加"."存入最后的结果集。

public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<String>();
if(s==null || s.length()<4 || s.length()>12) return result;

for(int i=1; i<4; i++){
String first = s.substring(0, i);
if(!isValid(first))
continue;
for(int j=1; j<4&&i+j<s.length(); j++){
String second = s.substring(i,i+j);
if(!isValid(second))
continue;
for(int k=1; k<4&&i+j+k<s.length(); k++){
String third = s.substring(i+j, i+j+k);
String fourth = s.substring(i+j+k, s.length());
if(!isValid(third) || !isValid(fourth))
continue;
String ip = first+"."+second+"."+third+"."+fourth;
result.add(ip);
}
}
}
return result;
}

private boolean isValid(String s){
if(s.length()>1 && s.charAt(0)=='0')
return false;
int ip = Integer.parseInt(s);
if(ip>=0 && ip<=255)
return true;

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  有效IP地址 LeetCode