-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
70 lines (54 loc) · 1.55 KB
/
Copy pathsolution.cpp
File metadata and controls
70 lines (54 loc) · 1.55 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution
{
public:
// Function to check if a segment is a valid IP part
bool isValid(string &s, int start, int len)
{
// Length should not exceed string
if (start + len > s.size())
return false;
// Leading zero check
if (len > 1 && s[start] == '0')
return false;
int num = 0;
// Convert substring to number
for (int i = start; i < start + len; i++)
{
num = num * 10 + (s[i] - '0');
}
return num <= 255;
}
void backtrack(string &s, int index, int parts, string current, vector<string> &result)
{
// If 4 parts formed and string consumed
if (parts == 4 && index == s.size())
{
current.pop_back(); // remove last dot
result.push_back(current);
return;
}
// If invalid condition
if (parts >= 4)
return;
// Try segment length 1 to 3
for (int len = 1; len <= 3; len++)
{
if (isValid(s, index, len))
{
string segment = s.substr(index, len);
backtrack(
s,
index + len,
parts + 1,
current + segment + ".",
result);
}
}
}
vector<string> generateIp(string &s)
{
vector<string> result;
backtrack(s, 0, 0, "", result);
return result;
}
};