Skip to content

Commit 44182f9

Browse files
Add files via upload
1 parent 92a5423 commit 44182f9

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// 典型的DFS
2+
3+
// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Restore IP Addresses.
4+
// Memory Usage: 8.5 MB, less than 91.67% of C++ online submissions for Restore IP Addresses.
5+
6+
class Solution
7+
{
8+
public:
9+
vector<string> restoreIpAddresses(string s)
10+
{
11+
vector<string> res;
12+
13+
getCandidate(s, "", res, 4);
14+
15+
return res;
16+
}
17+
private:
18+
void getCandidate(string input, string curStr, vector<string>& res, int numOfDigit)
19+
{
20+
// 边界条件处理
21+
if (input.length() < numOfDigit || input.length() > numOfDigit * 3)
22+
return ;
23+
24+
if (numOfDigit == 1)
25+
{
26+
if (atoi(input.c_str()) <= 255)
27+
{
28+
if (input.length() == 1)
29+
res.push_back(curStr + input);
30+
else if (input[0] != '0')
31+
res.push_back(curStr + input);
32+
}
33+
return ;
34+
}
35+
36+
for (int i = 1; i <= 3; ++i)
37+
{
38+
if (input.length() < i) return ;
39+
string substr = input.substr(0, i);
40+
41+
if (i < 3 || atoi(substr.c_str()) <= 255)
42+
getCandidate(input.substr(i), curStr + substr + '.', res, numOfDigit - 1);
43+
44+
if (input[0] == '0')
45+
break;
46+
}
47+
}
48+
};

0 commit comments

Comments
 (0)