LeetCode 93 Restore IP Addresses

简介:

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数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public  class  Solution 
{
     //深度优先遍历,DFS即可实现
     List<String> res= new  ArrayList<String>();
     public  List<String> restoreIpAddresses(String s) 
     {
         //特殊情况处理
         if (s== null  || s.length()<= 0  || s.length()< 4  || s.length()> 12 )
             return  res;
 
         String one= "" ;
         byDFS(s, 0 , 0 ,one);
         return  res;
     }
 
     //index 记录开始的位置,k记录截取的数量,
     void  byDFS(String s,  int  index, int  k,String one) 
     {
         if (k== 3 )
         {
             String tmp = s.substring(index, s.length());
             if (check(tmp))
                 res.add(one+tmp);
             return  ;
         } else
         {
             //每一次最长的截取长度是i,最短1位,最长3位
             for ( int  i= 1 ;i<= 3  && index+i < s.length() ;i++)
             {
                 String tmp = s.substring(index, index+i);
                 if (check(tmp))
                     byDFS(s, index+i, k+ 1 , one+tmp+ "." );
             }
         }
     }
 
     public  boolean  check(String ip) 
     {
         //以0开始的字符串,只有0是合理的,其余的比如001等等都不是合理的
         if (ip.charAt( 0 )== '0' )
         {
             if (ip.equals( "0" ))
                 return  true ;
             else
                 return  false ;
         } else
         {
             int  ipNum=Integer.parseInt(ip);
             if (ipNum> 0  && ipNum<= 255 )
                 return  true ;
             else
                 return  false ;
         }
     }
}

哎,映客线下笔试题。好难哦。虽然想到是回溯,但是没做出来,没想到是LT原题。gg。

本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1971550


相关文章
|
6月前
|
算法
代码随想录算法训练营第二十七天 | LeetCode 93. 复原 IP 地址、78. 子集、90. 子集 II
代码随想录算法训练营第二十七天 | LeetCode 93. 复原 IP 地址、78. 子集、90. 子集 II
35 0
|
7月前
|
算法
代码随想录Day23 回溯算法 LeetCode T93 复原ip地址 LeetCode T78子集 LeetCode T90 子集II
代码随想录Day23 回溯算法 LeetCode T93 复原ip地址 LeetCode T78子集 LeetCode T90 子集II
22 0
|
索引
LeetCode 93. Restore IP Addresses
给定一个用数字表示的字符串,把它们恢复成可能的IP地址.
41 0
LeetCode 93. Restore IP Addresses
|
C++ Python
LeetCode 929. Unique Email Addresses
LeetCode 929. Unique Email Addresses
68 0
LeetCode | 93. 复原 IP 地址
LeetCode | 93. 复原 IP 地址
75 0
代码随想录刷题|LeetCode 93.复原IP地址 78.子集 90.子集II
代码随想录刷题|LeetCode 93.复原IP地址 78.子集 90.子集II
|
存储 算法
LeetCode 92反转链表Ⅱ&93复制ip地址&94二叉树的中序遍历
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
68 0
LeetCode 92反转链表Ⅱ&93复制ip地址&94二叉树的中序遍历
|
存储 算法
☆打卡算法☆LeetCode 93、复原 IP 地址 算法解析
“给定一个只包含整数的字符串,表示一个IP地址,返回所有可能有效的IP地址,在这些地址中插入点来形成。”
|
5天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
8 0