Problem · String
Restore Addresses with K Segments
Learn this problemProblem statement
You are given a string digits containing only decimal digits and an integer segmentCount.
Insert exactly segmentCount - 1 dots so that every resulting segment:
- contains between one and three digits,
- represents an integer from
0through255, and - has no leading zero unless the segment is exactly
0.
Return every valid dotted address in lexicographic order. Return an empty array when no valid address exists.
When segmentCount = 4, this is the standard restoration rule for IPv4 addresses; other values use the same segment rules.
Function
restoreAddresses(digits: String, segmentCount: int) → String[]Examples
Example 1
digits = "25525511135"segmentCount = 4return = ["255.255.11.135","255.255.111.35"]Both outputs have four valid segments, and no other placement satisfies the value and leading-zero rules.
Example 2
digits = "010010"segmentCount = 4return = ["0.10.0.10","0.100.1.0"]A segment beginning with 0 must be exactly 0, which eliminates placements such as 01.
Example 3
digits = "1234"segmentCount = 2return = ["1.234","12.34","123.4"]With two segments, the dot may follow the first, second, or third digit, and every resulting segment remains at most 255.
Constraints
1 ≤ digits.length ≤ 30.digitscontains only decimal digits.1 ≤ segmentCount ≤ 10.- The total number of returned characters fits in memory.