题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
class Solution: def solve(self , IP: str) -> str: # write code here if '.' in IP: ip = IP.split('.') for i in ip: if len(i) > 3 or len(i) < 1: return "Neither" if i[0] == '0' and i[-1] != '0': return "Neither" for j in i: if (not '0' <= j <='9'): return "Neither" if int(i) > 255 or int(i) < 0: return "Neither" return "IPv4" if ':' in IP: ip = IP.split(':') for i in ip: if len(i) > 4 or len(i) < 1: return "Neither" for j in i: if (not '0' <= j <='9') and (not 'a' <= j <='f') and (not 'A' <= j <='F'): return "Neither" return "IPv6"
解题思路
由于IPv4和IPv6的要求不一样,因此分成了两种情况进行处理:
1.第一种是IPv4:
- 首先以'.'为分隔符切分字符串,然后遍历该字符串数组;
- 如果长度大于3或长度小于1,则返回‘Neither’;
- 如果首字母为0但是尾字母不为0,则返回'Nether';
- 如果字符串内的元素有不在0-9之间的,则返回‘Neither’;
- 如果字符串对应的数字大于255,则返回‘Neither’;
- 如果都满足,则返回‘IPv4’。
2.第二种是IPv6:
- 首先以':'为分隔符切分字符串,然后遍历该字符串数组;
- 如果长度大于4或长度小于1,则返回‘Neither’;
- 如果字符串内的元素有不在0-9之间且不在a-f之间且不在A-F之间的,则返回‘Neither’;
- 如果都满足,则返回‘IPv6’。
复杂度
- 时间复杂度为O(n);
- 空间复杂度为O(n)。