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

leetcode 93. Restore IP Addresses

时间:2015-02-20 19:44:42      阅读:197      评论: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)

[Solution]

三层循环,放置三个.位置并判断是否是合法ip地址.

 1 vector<string> restoreIpAddresses(string s) 
 2     {
 3         int i, j, k, n = s.size();
 4         string ip[4];
 5         vector<string> result;
 6         for (i = 1; i <= 3; i++)
 7         {
 8             for (j = i + 1; j <= i + 3; j++)
 9             {
10                 for (k = j + 1; k <= j + 3; k++)
11                 {
12                     if (n - k > 3 || n - k <= 0)
13                         continue;
14                     ip[0] = s.substr(0, i);
15                     ip[1] = s.substr(i, j - i);
16                     ip[2] = s.substr(j, k - j);
17                     ip[3] = s.substr(k, n - k);
18                     if (check(ip[0]) && check(ip[1]) && check(ip[2]) && check(ip[3]))
19                         result.push_back(ip[0] + . + ip[1] + . + ip[2] + . + ip[3]);
20                 }
21             }
22         }
23         
24         return result;
25     }
26         
27     bool check(string s)
28     {
29         if (s.size() == 1)
30             return true;
31         else if (s[0] == 0)
32             return false;
33         else if (atoi(s.c_str()) <= 0xff)
34             return true;
35         return false;
36     }

 

leetcode 93. Restore IP Addresses

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4296644.html

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