forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 39
/
restoreIPAddresses.cpp
75 lines (62 loc) · 1.83 KB
/
restoreIPAddresses.cpp
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
// Source : https://oj.leetcode.com/problems/restore-ip-addresses/
// Author : Hao Chen
// Date : 2014-08-26
/**********************************************************************************
*
* 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 <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void restoreIpAddressesHelper(string& s, int start, int partNum, string ip, vector<string>& result);
vector<string> restoreIpAddresses(string s) {
vector<string> result;
string ip;
restoreIpAddressesHelper(s, 0, 0, ip, result);
return result;
}
void restoreIpAddressesHelper(string& s, int start, int partNum, string ip, vector<string>& result) {
int len = s.size();
if ( len - start < 4-partNum || len - start > (4-partNum)*3 ) {
return;
}
if (partNum == 4 && start == len){
ip.erase(ip.end()-1, ip.end());
result.push_back(ip);
return;
}
int num = 0;
for (int i=start; i<start+3; i++){
num = num*10 + s[i]-'0';
if (num<256){
ip+=s[i];
restoreIpAddressesHelper(s, i+1, partNum+1, ip+'.', result);
}
//0.0.0.0 valid, but 0.1.010.01 is not
if (num == 0) {
break;
}
}
}
int main(int argc, char**argv)
{
string s = "25525511135";
if (argc>1){
s = argv[1];
}
vector<string> result = restoreIpAddresses(s);
cout << s << endl;
for(int i=0; i<result.size(); i++){
cout << '\t' << result[i] << endl;
}
return 0;
}