码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:Restore IP Addresses(存储IP地址)

时间:2015-11-10 17:50:56      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

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)

典型的dfs,但是要点是注意什么才是真的ip地址,代码如下:

 1 class Solution {
 2 public:
 3     vector<string> restoreIpAddresses(string s) {
 4         if (s.size() > 12) return ret;
 5         dfs(s, 0, 0);
 6         return ret;
 7     }
 8     
 9     bool check(string &s)
10     {
11         if (s.size() == 1)
12             return "0" <= s && s <= "9";
13         else if (s.size() == 2)
14             return "10" <= s && s <= "99";
15         else if (s.size() == 3)
16             return "100" <= s && s <= "255";
17         else
18             return false;
19     }
20 
21     void dfs(const string & s, int start, int nth)
22     {
23         if (nth == 4 && start != s.size())
24             return;
25         else if (nth == 4 && start == s.size()){
26             string tmp = "";
27             for (int i = 0; i < 3; ++i){
28                 tmp += tmpRes[i];
29                 tmp += ".";
30             }
31             tmp += tmpRes[3];    //为了凑格式
32             ret.push_back(tmp);
33         }
34         else
35             for (int i = 1; i < 4; ++i){
36                 if(start + i <= s.size()){
37                     string tmp = s.substr(start, i);
38                     if(check(tmp)){
39                         tmpRes.push_back(tmp);
40                         dfs(s, start + i, nth + 1);
41                         tmpRes.pop_back();
42                     }
43                 }
44             }
45     }
46 
47 private:
48     vector<string> tmpRes;
49     vector<string> ret;
50 };

写的有点乱了 ,见谅见谅

LeetCode OJ:Restore IP Addresses(存储IP地址)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4953672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!