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
| class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ result = [] self._restoreIpAddresses(0, s, [], result) return result
def _restoreIpAddresses(self, length, s, ips, result): if not s: if length == 4: result.append('.'.join(ips)) # 以.分隔作为字符串返回 return if length == 4: # 分了4段,结束 return # 取一位 self._restoreIpAddresses(length + 1, s[1:], ips + [s[:1]], result) # 若要取2位及以上,要确保目前的第一位不能为0 if s[0] != '0': if len(s) >= 2: self._restoreIpAddresses(length + 1, s[2:], ips + [s[:2]], result) if len(s) >= 3 and int(s[:3]) <= 255: # 若要取3位,则要保证小于255 self._restoreIpAddresses(length + 1, s[3:], ips + [s[:3]], result)
|