本文共 1369 字,大约阅读时间需要 4 分钟。
- 给定一个字符串,判断是否是有效的IP地址(提示,有效的IP地址格式是xxx.xxx.xxx.xxx, xxx在0-255之间)(输入不保证都是这种格式,要自己判断,同时001这种是否有效要问面试官)
去除开头的空格
输入:IP = "172.16.254.1"输出:"IPv4"解释:有效的 IPv4 地址,返回 "IPv4"
首先想最直接的,允许使用split函数的思路:
思路: 首先一定要有三个点,如果没有三个点,一定是不合法的。然后就可以用split,将每一部分单独拆分出来,变成四部分的字符串数组。
如果其中字符串的长度大于3或者为0,说明一定不合法。按照规定如果第一位是0,并且长度大于1,并且每个字符串只能是数字,而且值不超过255
def validIPv4(self, IP: str) -> bool: if IP.count('.')!=3: return False nums = IP.split('.') for x in nums: if len(x)==0 or len(x)>3: return False if x[0]=='0' and len(x)>1 or not x.isdigit() or int(x)>255: return False return True
纯C字符串解析:
bool judgeIPV4(char* s) { if (!s) return false; int digit = -1; count = 0; while (*s != '\0') { if (*s >= '0' && *s <= '9' && digit == -1) { digit = 0; } if (*s >= '0' && *s <= '9' && digit != -1) { int temp = *s - '0'; digit = digit * 10 + temp; if (digit > 255) { return false; } } else if(digit == '.') { if (digit < 0) { return false; } count += 1; if (count > 3) return false; digit = -1; } else { return false; } s++; } if (count != 3 || digit < 0) return false; return true;}
转载地址:http://vjqv.baihongyu.com/