-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRestore_IP_Addresses.cpp
More file actions
107 lines (93 loc) · 2.32 KB
/
Restore_IP_Addresses.cpp
File metadata and controls
107 lines (93 loc) · 2.32 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Source : https://oj.leetcode.com/problems/restore-ip-addresses/
// Author : zheng yi xiong
// Date : 2014-12-30
/**********************************************************************************
*
* 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)
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> vec_str;
int len = s.length();
if (4 > len || 12 < len)
{
return vec_str;
}
int ip1 = (0 < (len - 10)) ? (len - 10) : 0;
for ( ; (len - ip1 > 3) && ( (ip1 < 2) || ((2 == ip1) && IsIpAddress(s, 0)) ); ++ip1)
{
if ((0 < ip1) && ('0' == s[0]))
{
continue;
}
int ip2 = (ip1 + 1 < (len - 7))? (len - 7) : (ip1 + 1);
for (; (len - ip2 > 2)&& ( (ip2 < 3 + ip1) || ((ip2 == 3 + ip1) && IsIpAddress(s, ip1 + 1)) ); ++ip2)
{
if ( (ip2 > ip1 + 1) && ('0' == s[ip1 + 1]))
{
continue;
}
int ip3 = (ip2 + 1 < (len - 4))? (len - 4) : (ip2 + 1);
for (; (len - ip3 > 1) && ( (ip3 < 3 + ip2) || ((ip3 == 3 + ip2) && IsIpAddress(s, ip2 + 1)) ); ++ip3)
{
if ((ip3 > ip2 + 1) && ('0' == s[ip2 + 1]))
{
continue;
}
if (('0' == s[ip3 + 1]) && (len > ip3 + 2))
{
continue;
}
if (4 > len - ip3 || IsIpAddress(s, ip3 + 1) )
{
string str_ip = s.substr(0, ip1 + 1);
str_ip += '.';
str_ip += s.substr(ip1 + 1, ip2 - ip1);
str_ip += '.';
str_ip += s.substr(ip2 + 1, ip3 - ip2);
str_ip += '.';
str_ip += s.substr(ip3 + 1, len - ip3 - 1);
vec_str.push_back(str_ip);
}
}
}
}
return vec_str;
}
private:
bool IsIpAddress(string &s, int pos)
{
if ('2' > s[pos])
{
return true;
}
else if ('2' == s[pos])
{
if ('5' > s[pos + 1])
{
return true;
}
else if ('5' == s[pos + 1] && '5' >= s[pos + 2])
{
return true;
}
}
return false;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
string s = "25525511135";
Solution so;
vector<string> vec_str = so.restoreIpAddresses(s);
return 0;
}