Accepted recurssive python solution


  • 2
    L

    Function split2intgers need an additional input numDig to denote the number of integer that should separated from the string. At the beginning this number is 4. Then recursively check all possible cases.

      class Solution:
            # @param s, a string
            # @return a list of strings
            def split2intgers(self,string,numDig):
                res=[]
                if numDig==1: 
                    if len(string)==1 or (len(string)==2 and string[0]>'0') or (len(string)==3 and string[0]>'0' and int(string[0:3])<=255):
                        return [string]
                    else:
                        return []
                else:
                    if len(string)<numDig:
                        return []
                    for ii in range(1,min(len(string)-numDig+1,3)+1):
                        tmp=string[0:ii]
                        if len(tmp)==1 or (len(tmp)==2 and tmp[0]!='0') or (len(tmp)==3 and tmp[0]!='0' and int(tmp[0:3])<=255):
                            list=self.split2intgers(string[ii:],numDig-1)
                            if list:
                                res+=[string[0:ii]+'.'+elem for elem in list]
                return res
            def restoreIpAddresses(self, s):
                #should be seperate into four 
                res=self.split2intgers(s,4)
                return res

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.