Simple recursive Python solution


  • 0
    class Solution(object):
        def restoreIpAddresses(self, s):
            
            def create_ips(s, block, path, list_ret):
                if (block == 3 and len(s) > 3) or len(s) == 0:
                    return
                if block < 3:
                    for i in range(3):
                        this_block     = s[:i + 1]
                        rest_of_string = s[i + 1:]
                        if 0 <= int(this_block) <= 255:
                            if this_block[0] == "0" and len(this_block) > 1:
                                break
                            string = this_block + "."
                            create_ips(rest_of_string, block + 1, path + string, list_ret)
                else:
                    if 0 <= int(s) <= 255:
                        if not (s[0] == "0" and len(s) > 1):
                            list_ret.append(path + s)
                return
            
            list_ret = []
            create_ips(s, 0, "", list_ret)
            return list_ret

Log in to reply
 

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