noaman_wgs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
 1 package test2;
 2 
 3 import java.util.ArrayList;
 4 
 5 public class IPTest {  
 6     public static ArrayList<String> restoreIpAddresses(String s) {  
 7         ArrayList<String> res = new ArrayList<String>();  
 8         if (s == null || s.length() < 4 || s.length() > 12) {  
 9             return res;  
10         }  
11   
12         StringBuilder tmp = new StringBuilder();  
13   
14         depthFS(0, 0, s, tmp, res);  
15   
16         return res;  
17     }  
18   
19     public static void depthFS(int count, int index, String s, StringBuilder tmp,  
20             ArrayList<String> res) {  
21         if (count == 4 && index == s.length()) {  
22             res.add(tmp.toString().substring(0, tmp.length() - 1));  
23             return;  
24         } else {  
25             for (int i = 1; i <= 3 && index + i <= s.length(); i++) {  
26                 String tmpStr = s.substring(index, index + i);  
27                 if (isValid(tmpStr)) {  
28                     int bt = tmp.length();  
29                     int ed = tmp.length() + tmpStr.length();  
30                     tmp.append(tmpStr).append(".");  
31                     depthFS(count + 1, index + i, s, tmp, res);  
32                     tmp.delete(bt, ed + 1);  
33                 }  
34             }  
35         }  
36     }  
37   
38     public static boolean isValid(String s) {  
39         if (s.charAt(0) == '0') {  
40             return s.equals("0");  
41         }  
42   
43         int num = Integer.parseInt(s);  
44   
45         return num > 0 && num <= 255;  
46     }  
47     
48     
49     public static void main(String[] args) {
50         System.out.println(restoreIpAddresses("23343"));
51     }
52 } 

 

。私有IP地址范围:  

A类:10.0.0.0-10.255.255.255  

B类:172.16.0.0-172.31.255.255  

C类:192.168.0.0-192.168.255.255

编译器版本: Java 1.8.0_66

请使用标准输入输出(System.in, System.out);已禁用图形、文件、网络、系统相关的操作,如java.lang.Process , javax.swing.JFrame , Runtime.getRuntime;不要自定义包名称,否则会报错,即不要添加package answer之类的语句;您可以写很多个类,但是必须有一个类名为Main,并且为public属性,并且Main为唯一的public class,Main类的里面必须包含一个名字为'main'的静态方法(函数),这个方法是程序的入口

时间限制: 555S (C/C++以外的语言为: 557 S)   内存限制: 444M (C/C++以外的语言为: 956 M)

输入:

输入数据就是一行,仅仅包括数字的字符串

输出:

有效的ip地址字符串数组,如果没有解析到有效的ip字符串则输出空的字符串数组

输入范例:

1022111838

输出范例:

比如:102.21.118.38

102.211.18.38

posted on 2017-03-07 15:52  noaman_wgs  阅读(211)  评论(0编辑  收藏  举报