LeetCode-Restore IP Addresses

哎,写代码太不专注了,

还是头脑和注意力不够集中,

需要多在脑子里面磨练,

另外写程序的思维方式还比较土,

总喜欢单独考虑很多特殊情况,导致代码看起来很繁琐,

需要多看别人的代码好好学习如何写得简洁短小;

 1 class Solution {
 2 public:
 3     vector<string> restoreIpAddresses(string s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<string> res;
 7         if (s.empty() || s.size() < 4 || s.size() > 12) {
 8             return res;
 9         }
10         vector<string> ip;
11         get(res, ip, s, 0, 0);
12         return res;
13     }
14     void get(vector<string> &res, vector<string> &ip, string &s, int p, int num) {
15         if (num == 3) {
16             if (s.size() - p > 3) {
17                 return;
18             }
19             if (s[p] == '0' && p != s.size() - 1) {
20                 return;
21             }
22             int n = 0;
23             for (int i = p; i < s.size(); ++i) {
24                 n = n * 10 + s[i] - '0';
25             }
26             if (n > 255) {
27                 return;
28             }
29             string ipstr = s.substr(p, s.size() - p + 1);
30             string ret = ip[0] + "." + ip[1] + "." + ip[2] + "." + ipstr;
31             res.push_back(ret);
32             return;
33         }
34         if (s[p] == '0') {
35             ip.push_back(s.substr(p, 1));
36             int len = s.size() - p - 1;
37             int t = 3 - num;
38             if (len < t || len > 3 * t) {
39                 return;
40             }
41             get(res, ip, s, p + 1, num + 1);
42         }
43         else {
44             for (int i = 0; i < 3; ++i) {
45                 vector<string> nvec = ip;
46                 nvec.push_back(s.substr(p, i + 1));
47                 int len = s.size() - p - 1 - i;
48                 int t = 3 - num;
49                 if (len < t || len > 3 * t) {
50                     continue;
51                 }
52                 if (i == 2) {
53                     int temp = 100 * (s[p] - '0') + 10 * (s[p + 1] - '0') + (s[p + 2] - '0');
54                     if (temp > 255) {
55                         continue;
56                     }
57                 }
58                 get(res, nvec, s, p + i + 1, num + 1);
59             }
60         }
61     }
62 };

 

posted @ 2013-09-10 09:59  Exio  阅读(266)  评论(0编辑  收藏  举报