Simple Python code: using iteration and filter


  • 0
    M

    A simple Python solution using iteration and filter

        def restoreIpAddresses(self, s):
            def ipcheck(s):
                try:
                    arr = s.split('.')
                    for x in arr:
                        if int(x) > 255:    return False
                        if int(x) != 0 and len(x) != int(math.log(int(x), 10)) + 1:
                            return False
                        if x in ["00", "000", "000"]:   return False
                except ValueError:
                    return False
                return True
    
            def ipstr(s, left, mid, right):
                return s[0:left] + '.' + s[left:mid] + '.' + s[mid:right] + '.' + s[right:]
    
            n = len(s) + 3
            if n > 15:  return []
            return filter(ipcheck,
                [ ipstr(s, left, mid, right)
                    for mid in range(1, n-1)
                    for right in range(mid+1, n-1)
                    for left in range(0, mid)
                ]
            )
    

Log in to reply
 

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