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)

 1 class Solution {
2 public:
3
5         // Start typing your C/C++ solution below
6         // DO NOT write int main() function
7         int i=0,j,k;
8         int len = s.size();
9         vector<string> result;
10         if (len>12 || len< 4)
11             return result;
12         for(i;i<len-3;i++){
13             for(j=i+1;j<len-2;j++){
14                 for(k=j+1;k<len-1;k++){
15                     string s1 = s.substr(0,i+1);
16                     string s2 = s.substr(i+1,j-i);
17                     string s3 = s.substr(j+1,k-j);
18                     string s4 = s.substr(k+1);
19                     if(isOK(s1) && isOK(s2) && isOK(s3) && isOK(s4)){
20                         string s5 = s1 + "." + s2 + "." + s3 + "." + s4;
21                         result.push_back(s5);
22                     }
23                 }
24             }
25         }
26         return result;
27     }
28
29     bool isOK(string s){
30         int len = s.size();
31         if (len>3 || len <1)
32             return false;
33         else if (1==len)
34             return true;
35         else if (2==len){
36             return ('0'!=s.at(0));
37         }else{//3==len
38             int a = (s.at(0)-'0')*100 + (s.at(1)-'0')*10+(s.at(2)-'0');
39             return (a>=100 && a<=255);
40         }
41     }
42 };

posted on 2013-09-24 00:01  Horstxu  阅读(487)  评论(0编辑  收藏  举报