Leetcode練習(python):字符串類:第93題:復原IP地址:給定一個只包含數字的字符串,復原它並返回所有可能的 IP 地址格式。 有效的 IP 地址正好由四個整數(每個整數位於 0 到 255 之間組成),整數之間用 '.' 分隔。


題目:
復原IP地址:給定一個只包含數字的字符串,復原它並返回所有可能的 IP 地址格式。  有效的 IP 地址正好由四個整數(每個整數位於 0 到 255 之間組成),整數之間用 '.' 分隔。 
思路:
思路較簡單。
程序:
class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        if not s:
            return []
        length = len(s)
        if length < 4:
            return []
        result = []
        for index1 in range(1, 4):
            section1 = s[0: index1]
            if self.judgeIfValid(section1):
                for index2 in range(index1 + 1, index1 + 4):
                    section2 = s[index1: index2]
                    if self.judgeIfValid(section2):
                        for index3 in range(index2 + 1, index2 + 4):
                            section3 = s[index2: index3]
                            if self.judgeIfValid(section3):
                                section4 = s[index3:]
                                if self.judgeIfValid(section4):
                                    result.append("%s.%s.%s.%s" %(section1, section2, section3, section4))
        ip = result
        return ip
    def judgeIfValid(self, section):
        if section and section[0] == "0"  and len(section) > 1:
            return False
        if section and int(section) == 0 and len(section) > 1:
            return False
        if section and len(section) > 3:
            return False
        if section and int(section) >= 0 and int(section) <= 255:
            return True
        else:
            return False


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM