1 line straightforward Python


  • 0

    One line version, just go over all the possible combinations. Keep in mind to check if leading zero exists.

    class Solution(object):
        def restoreIpAddresses(self, s):
            """
            :type s: str
            :rtype: List[str]
            """
            return [".".join((s[:a],s[a:b],s[b:c],s[c:])) \
                    for a in range(1,4) for b in range(a+1,a+4) for c in range(b+1,b+4) \
                    if 0 < len(s)-c < 4 and all(int(x) < 256 and str(int(x)) == x \
                    for x in (s[:a],s[a:b],s[b:c],s[c:]))]
    

    Original 9 lines version for readability.

    class Solution(object):
        def restoreIpAddresses(self, s):
            """
            :type s: str
            :rtype: List[str]
            """
            n, res = len(s), []
            for a in range(1,4):
                for b in range(a+1,a+4):
                    for c in range(b+1,b+4):
                        if 0 < n-c < 4:
                            tmp = (s[:a], s[a:b], s[b:c], s[c:])
                            if all(int(x) < 256 and str(int(x)) == x for x in tmp):
                                res.append(".".join(tmp))
            return res
    

Log in to reply
 

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