[AlgoExpert] Valid IP Addresses

Valid IP Addresses

  • Time : O(1)
  • Space : O(1)
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
#include <vector>
using namespace std;
void helper(vector<string>& res, int pos, string& s, string build, int depth) {
if(depth == 4) {
if(pos == s.length()) {
build.pop_back();
res.push_back(build);
}
} else {
int token = 0, len = s.length();
string tk = "";
for(int i = pos; i < max(len, pos + 3); i++) {
token = token * 10 + (s[i] & 0b1111);
tk.push_back(s[i]);
if(token < 0 or token > 255) break;
if(to_string(token).length() != i - pos + 1) break;
helper(res, i + 1, s, build + tk + '.', depth + 1);
}
}
}
vector<string> validIPAddresses(string s) {
vector<string> res;
helper(res, 0, s, "", 0);
return res;
}

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