首页 > 技术文章 > lintcode-【中等】恢复IP地址

Shirlies 2016-02-29 20:45 原文

题目

给一个由数字组成的字符串。求出其可能恢复为的所有IP地址。链接

样例

给出字符串 "25525511135",所有可能的IP地址为:

[
  "255.255.11.135",
  "255.255.111.35"
]

答案

直接暴力遍历就行了,只不过需要注意的是0,以及数字是不能有前缀0。

代码

 1 class Solution {
 2 private:
 3     int strToInt(const string &str)
 4     {
 5         int ans = 0;
 6         int len = str.size();
 7         
 8         if(len > 1 && str[0] == '0')
 9         {
10             return 256;
11         }
12         
13         for(int i = 0; i < len; ++ i)
14         {
15             ans = (ans * 10 + str[i] - '0');
16         }
17         
18         return ans;
19     }
20     
21 public:
22     /**
23      * @param s the IP string
24      * @return All possible valid IP addresses
25      */
26     vector<string> restoreIpAddresses(string& s) {
27         // Write your code here
28         int len = s.size();
29         vector<string> ans;
30         string result;
31         
32         string first;
33         string second;
34         string third;
35         string fourth;
36         int iFirst,iSecond,iThird,iFourth;
37         for(int i = 0;i < len - 3; ++ i)
38         {
39             first.push_back(s[i]);
40             iFirst = strToInt(first);
41             if(iFirst > 255)
42             {
43                 break;
44             }
45             
46             second.clear();
47             for(int j = i + 1; j < len - 2; ++ j)
48             {
49                 second.push_back(s[j]);
50                 iSecond = strToInt(second);
51                 if(iSecond > 255)
52                 {
53                     break;
54                 }
55                 
56                 third.clear();
57                 for(int k = j + 1;k < len - 1; ++ k)
58                 {
59                     third.push_back(s[k]);
60                     iThird = strToInt(third);
61                     if(iThird > 255)
62                     {
63                         break;
64                     }
65                     
66                     fourth.clear();
67                     for(int l = k + 1;l < len; ++ l)
68                     {
69                         fourth.push_back(s[l]);
70                     }
71                     iFourth = strToInt(fourth);
72                     if(iFourth <= 255)
73                     {
74                         result = first + "." + second + "." + third + "." + fourth;
75                         ans.push_back(result);
76                     }
77                         
78                     
79                 }
80             }
81         }
82         
83         return ans;
84     }
85 };
View Code

我自己写的字符串转数字的方法,尽管知道可以使用sstream转换或者说使用atoi,而且以前都是使用sstream,但是还是想自己动动手玩玩。

推荐阅读