博客
关于我
微软高频面试模拟题: 验证合法的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/

你可能感兴趣的文章
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>
mysqldump备份时忽略某些表
查看>>