博客
关于我
微软高频面试模拟题: 验证合法的ipv4地址
阅读量:225 次
发布时间:2019-03-01

本文共 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/

你可能感兴趣的文章
mysql5.5和5.6版本间的坑
查看>>
mysql5.5最简安装教程
查看>>
mysql5.6 TIME,DATETIME,TIMESTAMP
查看>>
mysql5.6.21重置数据库的root密码
查看>>
Mysql5.6主从复制-基于binlog
查看>>
MySQL5.6忘记root密码(win平台)
查看>>
MySQL5.6的Linux安装shell脚本之二进制安装(一)
查看>>
MySQL5.6的zip包安装教程
查看>>
mysql5.7 for windows_MySQL 5.7 for Windows 解压缩版配置安装
查看>>
Webpack 基本环境搭建
查看>>
mysql5.7 安装版 表不能输入汉字解决方案
查看>>
MySQL5.7.18主从复制搭建(一主一从)
查看>>
MySQL5.7.19-win64安装启动
查看>>
mysql5.7.19安装图解_mysql5.7.19 winx64解压缩版安装配置教程
查看>>
MySQL5.7.37windows解压版的安装使用
查看>>
mysql5.7免费下载地址
查看>>
mysql5.7命令总结
查看>>
mysql5.7安装
查看>>
mysql5.7性能调优my.ini
查看>>
MySQL5.7新增Performance Schema表
查看>>