Leetcode: Restore IP Addresses

Question

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given “25525511135”,

return [“255.255.11.135”, “255.255.111.35”]. (Order does not matter)

Show Tags
Have you met this question in a real interview? Yes No
Discuss

My first try

class Solution(object):
    def restoreIpAddresses(self, s):
        """ :type s: str :rtype: List[str] """

        res = []
        if s=='':
            return res

        self.helper(s, 0, 3, '', res)
        return res

    def helper(self, s, start, part, item, res):
        if part==0:
            if len(s)-start>3:
                return
            else:
                if self.check(s[start:]):
                    res.append(item+s[start:])
                return 

        for ind in range( start,min(start+3,len(s)-1) ):
            # add '.'
            if self.check(s[start:ind+1]):
                self.helper(s, ind+1, part-1, item+s[start:ind+1]+'.', res)

    def check(self, s):
        if s=='':
            return True

        return True if int(s)>=0 and int(s)<256 else False

Error output:
0100110
0.100.1.10 is right, but 0.1.001.10 is not.

My Solution

class Solution(object):
    def restoreIpAddresses(self, s):
        """ :type s: str :rtype: List[str] """

        res = []
        if s=='':
            return res

        self.helper(s, 0, 3, '', res)
        return res

    def helper(self, s, start, part, item, res):
        if part==0:
            if len(s)-start>3:
                return
            else:
                if self.check(s[start:]):
                    res.append(item+s[start:])
                return 

        for ind in range( start,min(start+3,len(s)-1) ):   # the range is less than 3
            if self.check(s[start:ind+1]):
                self.helper(s, ind+1, part-1, item+s[start:ind+1]+'.', res)

    def check(self, s):
        if s=='':
            return True

        if len(s)>1:
            for elem in s:
                if elem!='0':
                    break
                else:
                    return False

        return True if int(s)>=0 and int(s)<256 else False



你可能感兴趣的:(Leetcode: Restore IP Addresses)