-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21_restoreipaddress.cpp
More file actions
49 lines (40 loc) · 1.34 KB
/
21_restoreipaddress.cpp
File metadata and controls
49 lines (40 loc) · 1.34 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
//https://leetcode.com/problems/restore-ip-addresses/description/
class Solution {
public:
bool allZeroes(string s){
for(int i=0 ; i<s.size() ; i++){
if(s[i]!='0') return false;
}
return true;
}
bool isValid(string s){
if(s.size()<=0) return false;
if(s.size()==1){
return true;
}
if(allZeroes(s) and s.size()>1) return false;
if(s[0]=='0') return false;
if(stoll(s)>255) return false;
return true;
}
vector<string> restoreIpAddresses(string s) {
set<string> ans;
int n = s.size();
for(int i=0 ; i<n ; i++){
for(int j=i+1; j<n ; j++){
for(int k = j+1 ; k<n ; k++ ){
string curr = s.substr(0 , i+1) + "." + s.substr(i+1 , j-i) + "."
+ s.substr(j+1 , k-j) + "." +
s.substr(k+1);
if(
isValid(s.substr(0 , i+1)) and isValid(s.substr(i+1 , j-i))
and isValid(s.substr(j+1 , k-j)) and isValid(s.substr(k+1))
){
ans.insert(curr);
}
}
}
}
return vector(ans.begin() , ans.end());
}
};