LintCode: Restore IP Address

简介:

string::substr(start_pos, length)

vector::push_back(element)

复制代码
 1 class Solution {
 2 public:
 3     vector<string> restoreIpAddresses(string s) {
 4         vector<string> ret;
 5         if(s.size() > 12)
 6             return ret;
 7         for(int i = 0; i < s.size(); i ++)
 8         {// [0, i]
 9             string ip1 = s.substr(0, i+1);
10             if ( !check(ip1) ) break;
11             for(int j = i+1; j < s.size(); j ++)
12             {// [i+1, j]
13                 string ip2 = s.substr(i+1, j-i);
14                 if ( !check(ip2) ) break;
15                 for(int k = j+1; k < s.size()-1; k ++)
16                 {// [j+1, k], [k+1, s.size()-1]
17                     string ip3 = s.substr(j+1, k-j);
18                     string ip4 = s.substr(k+1);
19                     if(check(ip3) && check(ip4))
20                     {
21                         string ip = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
22                         ret.push_back(ip);
23                     }
24                 }
25             }
26         }
27         return ret;
28     }
29     bool check(string ip)
30     {
31         int value = stoi(ip);
32         if(ip[0] == '0')    return ip.size() == 1;
33         return value <= 255 ? true : false;
34     }
35 };
复制代码

 


本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5108960.html,如需转载请自行联系原作者

相关文章
poj 2105 IP Address
题目链接
26 0
|
6月前
|
网络架构 开发者
成功解决The selected network interface is not valid
成功解决The selected network interface is not valid
成功解决The selected network interface is not valid
|
索引
LeetCode 93. Restore IP Addresses
给定一个用数字表示的字符串,把它们恢复成可能的IP地址.
60 0
LeetCode 93. Restore IP Addresses
POJ 2105 IP Address
POJ 2105 IP Address
114 0
|
JavaScript
题解 CF948A 【Protect Sheep】
题目链接 额。。这道题亮点在:$you$ $do$ $not$ $need$ $to$ $minimize$ $their$ $number.$所以说嘛。。。直接判断狼的四周有没有紧挨着的羊,没有的话,就直接空地全填狗输出。
995 0