Restore IP Addresses

 1 public class Solution {
 2     public static ArrayList<String> restoreIpAddresses(String s) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         ArrayList<String> result = new ArrayList<String>();
 6         if (s == null || s.length() == 0) {
 7             return result;
 8         }
 9         int depth = 0, start = 0;
10         String ip = "";
11         generate(s, start, depth, result, ip);
12 
13         return result;
14     }
15 
16     private static void generate(String s, int start, int depth,
17             ArrayList<String> result, String ip) {
18         // max = 3 check it
19         if ((s.length() - start) > (4 - depth) * 3) {
20             return;
21         }
22         // min = 1 check it
23         if (s.length() - start < 4 - depth) {
24             return;
25         }
26         if (depth == 4) {
27             ip = ip.substring(0, ip.length() - 1);
28             if(!result.contains(ip))
29                 result.add(ip);
30             return;
31         }
32 
33         int num = 0;
34         for (int i = start; i < Math.min(start + 3, s.length()); i++) {
35             num = num * 10 + (s.charAt(i) - '0');
36             if (num <= 255) {
37                 generate(s, i + 1, depth + 1, result, ip + num + ".");
38             }
39             if(num == 0){
40                 break;
41             }
42         }
43     }
44 }

 

posted on 2013-11-20 10:11  JasonChang 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jasonC/p/3432845.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值