Python iterative solution


  • 0
    A
    class Solution:
        # @param {string} s
        # @return {string[]}
        def restoreIpAddresses(self, s):
            n=len(s)
            ans=[]
            for i in range(1,4):
                for j in range(1,4):
                    for k in range(1,4):
                        for l in range(1,4):
                            if (i+j+k+l==n) and not(i>1 and s[0:i][0]=='0') and int(s[0:i])<256 and not(j>1 and s[i:i+j][0] == '0') and int(s[i:i+j])<256 and not(k>1 and s[i+j:i+j+k][0] == '0') and int(s[i+j:i+j+k])<256 and not(l>1 and s[i+j+k:i+j+k+l][0] == '0') and int(s[i+j+k:i+j+k+l])<256:
                                ans.append(s[0:i]+'.'+s[i:i+j]+'.'+s[i+j:i+j+k]+'.'+s[i+j+k:i+j+k+l])
            return ans

  • 0
    Z

    Thank you for providing this alternative thought... although I do think so many conditions are hard to control in an interview.


  • 0
    T

    It's not that complicated if the code writer has some respect for the readers:

    if i+j+k+l == n:
    	part1,part2,part3,part4 = s[0:i], s[i:i+j], s[i+j:i+j+k], s[i+j+k:n]
    	if  not(i>1 and part1[0] == '0') and int(part1)<256
    	and not(j>1 and part2[0] == '0') and int(part2)<256
    	and not(k>1 and part3[0] == '0') and int(part3)<256
    	and not(l>1 and part4[0] == '0') and int(part4)<256:
    		ans.append(part1+'.'+part2+'.'+part3+'.'+part4)
    

    (Syntax may be off a little, I'm not familiar with Python.)

    An even simpler alternative would be an isValid(s,i,j) method, but then you have to substring twice.


Log in to reply
 

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