问题:
难度:easy
说明:
我看题目本来以为是什么特别的算法,不过似乎都是业务做法,就是验证ipv4和ipv6,两种地址有不同特征
ipv4:0 ~ 255,不超过3位数,每个数字开头不带0,4串数组成,用 '.' 进行分割,以数字开头或者结尾。
ipv6:0 ~ 0xFFFF,不超过4位数,每个数字开头可以带0,0可以缩写(就是去掉,比如0001可以写成1),用 ':' 分割,8串数组成,以数字开头和结尾。
两者都不带正负号
问题链接:https://leetcode.com/problems/validate-ip-address/
输入案例:
Example 1:
Input: "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".
Example 2:
Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: This is a valid IPv6 address, return "IPv6".
Example 3:
Input: "256.256.256.256"
Output: "Neither"
Explanation: This is neither a IPv4 address nor a IPv6 address.
我的代码:
貌似直接做没有什么特别的好做法,如果写正则可能简单很多,不过我并不会。
class Solution {
public String validIPAddress(String IP) {
// 排除自身分隔符开头结尾
if(IP == null || "".equals(IP)
|| ':' == IP.charAt(IP.length() - 1) || '.' == IP.charAt(IP.length() - 1))
return "Neither";
String[] ipv4 = IP.split("\\.");
// 限制为 4 串数
if(ipv4.length == 4) {
// 任何报错都返回不正确,挺暴力的
try{
for(String ip : ipv4) {
char first = ip.charAt(0);
// 必须限制 0 ~ 9 字符,不以 0 开头,0 ~ 3位数
if(ip.length() > 3 || (ip.length() > 1 && '0' == first)
|| '0' > first || '9' < first)
return "Neither";
if(Integer.valueOf(ip) / 256 != 0)
return "Neither";
}
} catch(Exception e) {
return "Neither";
}
return "IPv4";
// 只有发现 1 串数,才进行切割
} else if(ipv4.length == 1) {
// 必须要 8 串数
String[] ipv6 = IP.split(":");
if(ipv6.length == 8) {
try{
for(String ip : ipv6) {
char first = ip.charAt(0);
// 必须不以 - + 开头,0 ~ 4位数,其他都交给trycatch
if(ip.length() > 4|| '-' == first || '+' == first)
return "Neither";
if(Integer.parseInt(ip,16) / 0xffff != 0)
return "Neither";
}
} catch(Exception e) {
return "Neither";
}
return "IPv6";
}
}
return "Neither";
}
}
其它代码:
官方的牛逼正则
import java.util.regex.Pattern;
class Solution {
String chunkIPv4 = "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
Pattern pattenIPv4 =
Pattern.compile("^(" + chunkIPv4 + "\\.){3}" + chunkIPv4 + "$");
String chunkIPv6 = "([0-9a-fA-F]{1,4})";
Pattern pattenIPv6 =
Pattern.compile("^(" + chunkIPv6 + "\\:){7}" + chunkIPv6 + "$");
public String validIPAddress(String IP) {
if (pattenIPv4.matcher(IP).matches()) return "IPv4";
return (pattenIPv6.matcher(IP).matches()) ? "IPv6" : "Neither";
}
}