Fork me on GitHub

Restore IP Addresses

Description

https://leetcode.com/problems/restore-ip-addresses/description/

Solution

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
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ret;
if (s.size() > 12 || s.size() < 4) return ret;
int index = 0;
vector<char> cur;
check(ret, s, 0, cur, 0);
return ret;
}
bool valid(string& s, int start, int bias) {
if (bias > 3) return false;
if (s[start] == '0' && bias > 1) return false;
if (bias < 3) return true;
int target = s[start] - '0';
target = 10 * target + s[start + 1] - '0';
target = 10 * target + s[start + 2] - '0';
return (target <= 255);
}

void check(vector<string>& ret, string& s, int start, vector<char>& cur, int depth) {
int size = s.size();

if (start == size) {
if (depth == 4) {
string s(cur.begin(), cur.end() - 1); //Skip the last '.'
ret.push_back(s);
}else
return;
}

int bias = 1;
while (start + bias <= size && bias <= 3) {
if ( !valid(s, start, bias) ) break;
cur.push_back(s[start + bias - 1]);
cur.push_back('.');
check(ret, s, start + bias, cur, depth + 1);
cur.pop_back();
++bias;
}
while (bias > 1) {cur.pop_back(); --bias; }
return;
}
};