1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

#include <vector>
#include <string>
#include <iostream>

using namespace std;

void restoreIpAddresses(string &s, string &ip, int pos, int segIndex, vector<string> &result) {
    if (segIndex > 4) {
        if (s.length() == pos) {
            ip.erase(ip.size()-1);
            result.push_back(ip);
        }
        return;
    }

    size_t size = ip.size();
    
    int seg = 0;
    for (int i = 0; i < 3 && pos < s.length(); ++i, ++pos) {
        seg = seg*10 + (s[pos] - '0');
        if (seg >= 256) break;
        
        ip.push_back(s[pos]);
        ip.push_back('.');
        restoreIpAddresses(s, ip, pos+1, segIndex+1, result);
        ip.erase(ip.size()-1);
        
        if (seg == 0) break;
    }
    
    ip.erase(size);
}


vector<string> restoreIpAddresses(string s) {
    vector<string> result;
    vector<size_t> indics;
    string ip = "";
    restoreIpAddresses(s, ip, 0, 1, result);
    
    return result;
}

ostream &operator<<(ostream &out, const vector<string> &v) {
    
    for (int i = 0; i < v.size(); ++i) {
        cout<< v[i] << ", ";
    }
    
    cout << endl;
    return out;
}

int main (int argc, const char * argv[]) {
    
    cout << restoreIpAddresses("010010") << endl;
    cout << restoreIpAddresses("10101010") << endl;
    cout << restoreIpAddresses("123123123") << endl;
    
    return 0;
}
View Program Text


Test Status