Leetcode 468. 验证IP地址
题目
编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。
IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1;
同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。
IPv6 地址由8组16进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如, 2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。
然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 ( :: ) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。
同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。
说明:
你可以认为给定的字符串里没有空格或者其他特殊字符。
测试样例
示例 1:
输入: "172.16.254.1"
输出: "IPv4"
解释: 这是一个有效的 IPv4 地址, 所以返回 "IPv4"。
示例 2:
输入: "2001:0db8:85a3:0:0:8A2E:0370:7334"
输出: "IPv6"
解释: 这是一个有效的 IPv6 地址, 所以返回 "IPv6"。
示例 3:
输入: "256.256.256.256"
输出: "Neither"
解释: 这个地址既不是 IPv4 也不是 IPv6 地址。
题解
模拟
我们先根据给定的IP地址确定IPV4还是IPV6,如果含有‘.’,则说明是IPV4;含有‘:’,则说明是IPV6
对于IPV4:
- 其中只能含有数字和’.’,且’.'只能含有3个,对于其中的数要小于等于255,还不能含有前导0
对于IPV6: - 其中可以含有数字,‘:’,A~F,a ~ f
- 数字获字母的位数不能超过4位
- ‘:’只能含有7个
详细过程见代码
代码
string validIP4Address(string IP){
int len = IP.length();
if(IP[len-1]=='.') return "Neither"; //最后一个位置一定不是符号
int i=0,j;
int time=0;
while(i < len){
for(j=i; j<len; j++){
if(IP[j] == '.'){ //找到点的位置
time++;
break;
}
if(IP[j] == ':' || IP[j]=='-') return "Neither";
if(IP[j]>='a'&&IP[j]<='z' || IP[j]>='A'&&IP[j]<='Z') return "Neither";
}
if(j-i != 1){ //如果只是1位数,则肯定符合要求
if(j-i>3 || IP[i] == '0') return "Neither"; //前者是4位数,一定不合要求;后者是2、3位数不能有前导0
string now = IP.substr(i,j-i);
if(stoi(now) > 255) return "Neither";
}
if(j+1<len && IP[j+1] == '.') return "Neither"; //点于点不能挨着
i = j+1;
if(time>3) return "Neither"; //超过4个点
}
if(time != 3) return "Neither";
return "IPv4";
}
string validIP6Address(string IP){
int len = IP.length();
if(IP[len-1]==':') return "Neither"; //最后一个位置一定不是符号
int i=0,j,time=0;
while(i < len){
for(j=i; j<len; j++){ //获取冒号的位置
if(IP[j] == ':'){
time++;
break;
}
if(IP[j] == '.' || IP[j]=='-') return "Neither";
if(IP[j]>='g'&&IP[j]<='z' || IP[j]>='G'&&IP[j]<='Z') return "Neither";
}
if(i==j || j-i>4) return "Neither"; //前者两个:挨着;后者为数位超过4位
i = j+1;
if(time>7) return "Neither";
}
if(time != 7) return "Neither";
return "IPv6";
}
string validIPAddress(string IP) {
int len = IP.length();
int choice=0;
for(int i=0; i<5; i++){
if(IP[i]=='.'){
choice = 4;
break;
}else if(IP[i]==':'){
choice = 6;
break;
}
}
switch(choice){
case 0:return "Neither";
case 4:return validIP4Address(IP);
case 6:return validIP6Address(IP);
}
return "";
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-ip-address
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。