美文网首页
leetcode93 Restore IP Addresses

leetcode93 Restore IP Addresses

作者: 就是果味熊 | 来源:发表于2020-06-22 09:12 被阅读0次

原文地址:https://leetcode.com/problems/restore-ip-addresses/

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

A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.

Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        def backtrack(s,ip,ips,times):
            if times == 4 and (not s):
                ips.append(ip[1:])
            for i in range(1, 4):
                if i <= len(s):
                    if len(s[:i]) > 1 and s[0] == "0":
                        break
                    elif int(s[:i]) <= 255:
                        backtrack(s[i:], ip + "." + s[:i], ips, times+1)
            return
        
        if len(s) > 12 or len(s) < 4: return []
        ips = []
        backtrack(s,"",ips,0)
        return ips

相关文章

网友评论

      本文标题:leetcode93 Restore IP Addresses

      本文链接:https://www.haomeiwen.com/subject/trgtfktx.html