defrestoreIpAddresses(s, res): res = [] for i inrange(0,4): for j inrange(i,i+4): if j >= len(s): break for k inrange(j, j+4): if k >= len(s): break s1 = s[0:i] s2 = s[i:j] s3 = s[j:k] s4 = s[k:] if isValid(s1) and isValid(s2) and isVAlid(s3) and isValid(s4): res.append(s1+'.'+s2+'.'+s3+'.'+s4) return res
classSolution(object): defrestoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ # split the string into 4 part res = [] self.getip(s, 4, "", res) return res
defgetip(self, s, k, out, result): """ s : input str out : result str result : all possible result k : k-th part """ if k == 0: iflen(s) == 0: result.append(out) else: # 0-3 每段最长3 for i inrange(4): # len(s) >= i 保证足够分的 iflen(s) >= i and self._isValid(s[0:i]): # k==1 即最后一段了 if k == 1: self.getip(s[i:], k-1, out+s[0:i], result) else: self.getip(s[i:], k-1, out+s[0:i]+'.', result) return result def_isValid(self, s): iflen(s) == 0orlen(s) > 3or (len(s)>1and s[0] =='0'): returnFalse return0 <= int(s) <= 255