题解 | #验证IP地址#

验证IP地址

https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880?tpId=295&tqId=1024725&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
#
class Solution:
    def solve(self , IP: str) -> str:
        # write code here
        L2=[]
        for i in range(9):
            L2.append(str(i))
        for i in range(ord("a"),ord("f")+1):
            L2.append(chr(i))
        for i in range(ord("A"),ord("F")+1):
            L2.append(chr(i))


        if ":" in IP:
            L = IP.split(":")
            if len(L)!=8:
                return "Neither"
            for x in range(len(L)):
                if len(L[x])>4:
                    return "Neither"

                if L[x] == "":
                    return "Neither"
                



                for i in range(len(L[x])):
                    if L[x][i] not in L2:
                        return "Neither"
            


                   
            return "IPv6"

        elif "." in IP:
            L = IP.split(".")
            if len(L)!=4:
                return "Neither"               
            for x in L:
                if not  x.isdigit():
                    return "Neither" 
                if x[0]=="0" and int(x)!=0:
                    return "Neither"       
            for x in L:
                if int(x) >255:
                    return "Neither"
            return "IPv4"

        else:
            return "Neither"

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务