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;
}
}
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;
}
}
相关文章推荐
- [leetcode.com]算法题目 - Restore IP Addresses
- Leetcode_restore-ip-addresses
- Leetcode--Restore IP Addresses
- Leetcode(93): Restore IP Addresses
- LeetCode--Restore IP Addresses
- Leetcode-Restore IP Addresses
- leetcode--Restore IP Addresses
- LeetCode Restore IP Addresses
- Leetcode: Restore IP addresses
- [LeetCode] Restore IP Addresses 解题报告
- LeetCode:Restore IP Addresses
- LeetCode之“字符串”:Restore IP Addresses
- leetcode--Restore IP Addresses
- [leetcode]Restore IP Addresses
- [Leetcode] Restore IP Addresses
- Leetcode Restore IP Addresses
- [LeetCode] Restore IP Addresses
- leetcode — restore-ip-addresses
- Leetcode : Restore IP Addresses
- leetcode第一刷_Restore IP Addresses