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

093. Restore IP Addresses

时间:2016-09-09 00:55:22      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

 1 class Solution {
 2 public:
 3     vector<string> restoreIpAddresses(string s) {
 4         vector<string> res;
 5         string current;
 6         if (s.size() > 12 || s.size() < 4) return res;
 7         else {
 8             checkIp(s, res, current, 0, 1);
 9             return res;
10         }
11     }
12 private:
13     void checkIp(string s, vector<string>& res, string& current, int startPos, int step)
14     {
15         if (startPos > s.size() - 1) return;
16         if (step == 4) {
17             if (startPos < s.size() - 3) return;
18             else {
19                 if (isValid(s, startPos, s.size() - 1)) {
20                     current.append(s, startPos, s.size() - startPos);
21                     res.push_back(current);
22                     current.erase(current.size() + startPos - s.size(), s.size() - startPos);
23                     return;
24                 }
25             }
26         }
27         else {
28             for (int i = 0; i < 3 && startPos + i < s.size(); ++i) {
29                 if (isValid(s, startPos, startPos + i)) {
30                     current.append(s, startPos, i + 1);
31                     current.push_back(.);
32                     checkIp(s, res, current, startPos + i + 1, step + 1);
33                     current.pop_back();
34                     current.erase(current.size() - i - 1, i + 1);
35                 }
36             }
37         }
38     }
39 
40     bool isValid(string s, int left, int right) {
41         if (s[left] == 0 && right > left) return false; // 这里需要判断如果以0开头,则只能有一位0
42         int num = 0;
43         for (int i = left; i <= right; ++i) {
44             num *= 10;
45             num += s[i] - 0;
46         }
47         if (num >= 0 && num < 256) return true;
48         else return false;
49     }
50 };

 

093. Restore IP Addresses

标签:

原文地址:http://www.cnblogs.com/shadowwalker9/p/5855029.html

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