力扣 468 合并区间
2020-10-28 本文已影响0人
zhaojinhui
题意:给定一个string,判断是否是合法字符串
思路:
- 查看IP是否为null或空,是就返回Neither
- 查看IP是否以'.'或':'结尾,是就返回Neither
- IP用'.' 分割,如果长度是4,那么就用IPv4的判断方程,核实每一个字段
- 否则,IP用':' 分割,如果长度是8,那么就用IPv6的判断方程,核实每一个字段
- 否则返回Neither
思想:字符串的组合
复杂度:时间O(n),空间O(n)
class Solution {
public String validIPAddress(String IP) {
if(IP == null || IP.length() == 0)
return "Neither";
if(IP.charAt(IP.length() - 1) == '.' || IP.charAt(IP.length() - 1) == ':')
return "Neither";
String[] IPs = IP.split("\\.");
if(IPs.length == 4) {
for(String ip: IPs) {
if(!isValidIPv4(ip))
return "Neither";
}
return "IPv4";
} else {
IPs = IP.split(":");
if(IPs.length == 8) {
for(String ip: IPs) {
if(!isValidIPv6(ip))
return "Neither";
}
return "IPv6";
}
return "Neither";
}
}
boolean isValidIPv4(String ip) {
if(ip.length() > 3 || ip.length() == 0)
return false;
if(ip.length() > 1 && ip.charAt(0) == '0')
return false;
int num = 0;
for(int i=0;i<ip.length();i++) {
char cur = ip.charAt(i);
if(cur < '0' || cur > '9')
return false;
num = num*10 + (cur - '0');
}
if(num > 255)
return false;
return true;
}
boolean isValidIPv6(String ip) {
if(ip.length() > 4 || ip.length() == 0)
return false;
for(int i=0;i<ip.length();i++) {
char cur = ip.charAt(i);
if((cur >= 'a' && cur <= 'f') || (cur >= 'A' && cur <= 'F') ||
(cur >= '0' && cur <= '9'))
continue;
else
return false;
}
return true;
}
}