[InterviewBit] Valid Ip Addresses

Valid Ip Addresses

  • Time :
  • Space :
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
void helper(string s, int p, vector<string>& res, string now, int cut = 0) {
if(cut == 3) {
if(p == s.length()) return;
if(p + 3 < s.length()) return;
if(s[p] == '0' and p + 1 != s.length()) return;
int part = stoi(s.substr(p));
if(0 <= part and part <= 255) {
now += s.substr(p);
res.push_back(now);
}
return;
}
if(s[p] == '0') helper(s,p+1,res,now + "0.", cut + 1);
else {
int part = 0;
for(int i = p; i < min(p + 3,(int)s.length()); i++) {
now.push_back(s[i]);
part = part * 10 + s[i] - '0';
if(0 <= part and part <= 255)
helper(s,i+1,res,now + ".", cut + 1);
}
}
}
vector<string> Solution::restoreIpAddresses(string A) {
vector<string> res;
helper(A,0,res,"");
sort(begin(res),end(res));
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/29/PS/interviewbit/valid-ip-addresses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.