Skip to content

Commit 76c8edd

Browse files
committed
https://leetcode.com/problems/restore-ip-addresses/
1 parent e26f7d8 commit 76c8edd

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

MediumProblems/RestoreIpAddress.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
namespace LeetCode.MediumProblems;
2+
3+
/// <summary>
4+
/// https://leetcode.com/problems/restore-ip-addresses/
5+
/// </summary>
6+
public class RestoreIpAddress
7+
{
8+
public IList<string> RestoreIpAddresses(string s) {
9+
List<string> result = new List<string>();
10+
if (s.Length < 4 || s.Length > 12) return result;
11+
Backtrack(s, 0, new List<string>(), result);
12+
return result;
13+
}
14+
15+
private void Backtrack(string s, int start, List<string> currentSegments, List<string> result) {
16+
if (currentSegments.Count == 4 && start == s.Length) {
17+
result.Add(string.Join(".", currentSegments));
18+
return;
19+
}
20+
if (currentSegments.Count == 4 || start >= s.Length) return;
21+
22+
for (int len = 1; len <= 3; len++) {
23+
if (start + len > s.Length) break;
24+
string segment = s.Substring(start, len);
25+
if (segment[0] == '0' && segment.Length > 1) continue;
26+
if (int.Parse(segment) > 255) continue;
27+
currentSegments.Add(segment);
28+
Backtrack(s, start + len, currentSegments, result);
29+
currentSegments.RemoveAt(currentSegments.Count - 1);
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)