力扣每日一题哈。
验证是否是一个正确的IP地址。
思路:
- 首先,把这个题细分一下,判断他是否是一个IPV4地址,或者ipv6地址。
- 然后判断IPV4和ipv6是否是有效的。
具体代码如下:
/**
* @author xnl
* @Description:
* @date: 2022/5/29 20:15
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
// String queryIP = "172.16.254.10";
//String queryIP = "2001:0db8:85a3:0:0:8A2E:0370:0";
// String queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334:";
// String queryIP = "12..33.4";
String queryIP = "20EE:FGb8:85a3:0:0:8A2E:0370:7334";
System.out.println(solution.validIPAddress(queryIP));
}
public String validIPAddress(String queryIP) {
// 是一个ipv4的地址
if (queryIP.contains(".")){
return isIpv4(queryIP);
} else {
return isIpv6(queryIP);
}
}
/**
* 是否是一个有效的IPV4地址
* @param queryIP
* @return
*/
private String isIpv4(String queryIP){
String[] split = queryIP.split("\\.");
if (split.length != 4 || queryIP.charAt(queryIP.length() - 1) == '.'){
return "Neither";
}
for (String str : split){
if (!isIpv4Int(str)){
return "Neither";
}
}
return "IPv4";
}
/**
* 是否是一个有效的IPV4整数
*/
private boolean isIpv4Int (String str){
int length = str.length();
// 去除首字母为空的情况
if (str.isEmpty() || (length > 1 && str.charAt(0) == '0')){
return false;
}
int temp = 0;
for (int i = 0; i < length; i++){
if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){
temp = temp * 10 + (str.charAt(i) - '0');
}else {
return false;
}
}
return temp >= 0 && temp <= 255;
}
/**
* 是否是一个有效的IPv6地址
* @param queryIP
* @return
*/
private String isIpv6(String queryIP){
String[] split = queryIP.split("\\:");
if (split.length != 8 || queryIP.charAt(queryIP.length() - 1) == ':'){
return "Neither";
}
for (String str : split) {
if (!isIpv6Int(str)){
return "Neither";
}
}
return "IPv6";
}
private boolean isIpv6Int(String str){
if (str.isEmpty() || str.length() > 4){
return false;
}
for (int i = 0; i < str.length(); i++){
if (!((str.charAt(i) >= '0' && str.charAt(i) <= '9') || (str.charAt(i) >= 'a' && str.charAt(i) <= 'f') ||
(str.charAt(i) >= 'A' && str.charAt(i) <= 'F'))){
return false;
}
}
return true;
}
}
如果有兴趣一起刷题的可以私聊我哈,一起学习。