算法
(模拟) $O(n)$
按题意模拟一下即可。
Java 代码
class Solution {
public String validIPAddress(String IP) {
String ip = IP.toLowerCase();
String[] ip4 = ip.split("\\.", -1);
if (ip4.length == 4) return checkIPv4(ip4);
String[] ip6 = ip.split(":", -1);
if (ip6.length == 8) return checkIPv6(ip6);
return "Neither";
}
public String checkIPv4(String[] ip) {
for (String s : ip) {
int n = s.length();
// check length
if (n == 0 || n > 3) return "Neither";
// check digits
for (int i = 0; i < n; ++i) {
if (!Character.isDigit(s.charAt(i))) return "Neither";
}
// check range
int num = Integer.valueOf(s);
if (num < 0 || num > 255) return "Neither";
// check leading zero
if (String.valueOf(num).length() < n) return "Neither";
}
return "IPv4";
}
public String checkIPv6(String[] ip) {
for (String s : ip) {
int n = s.length();
if (n == 0 || n > 4) return "Neither";
// check digits
for (int i = 0; i < n; ++i) {
char c = s.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') continue;
return "Neither";
}
}
return "IPv6";
}
}