Validate IP Address
纯模拟题,字符串的处理复杂,这里看起来IPv6的处理麻烦些,实际上还是传统的IPv4的先导零很复杂
class Solution(object):
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
if '.' in IP:
strings = IP.split('.')
if len(strings) != 4:
return 'Neither'
for string in strings:
if not string.isnumeric():
return 'Neither'
num = int(string)
if num == 0 and len(string) > 1:
return 'Neither'
if num > 0 and string[0] == '0':
return 'Neither'
if num < 0 or num > 255:
return 'Neither'
return 'IPv4'
elif ':' in IP:
strings = IP.split(':')
if len(strings) != 8:
return 'Neither'
for string in strings:
if len(string) > 4 or len(string) == 0:
return 'Neither'
for char in string:
if char.isalpha():
if char.upper() not in ['A', 'B', 'C', 'D', 'E', 'F']:
return 'Neither'
elif not char.isnumeric():
return 'Neither'
return 'IPv6'
return 'Neither'