思路
考察字符串的使用,还有对所有边界条件的检查
spilt(“\.”),toCharArray,Integer.parseInt()
代码
class Solution {boolean checkIpv4Segment(String str){if(str.length() == 0 || str.length() > 4) return false;if(str.charAt(0) == '0' && str.length() > 1) return false;for(char c:str.toCharArray()){if(c < '0' || c > '9'){return false;}}int num = Integer.parseInt(str);if(num < 0 || num > 255) return false;return true;}boolean checkIpv6Segment(String str){for(char c:str.toCharArray()){if( (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') ){return false;}}if(str.length() > 4 || str.length() == 0) return false;return true;}public String validIPAddress(String queryIP) {int dotLen = 0;int len = 0;for(int i = 0; i < queryIP.length(); i++){if(queryIP.charAt(i) == '.') dotLen++;else if(queryIP.charAt(i) == ':') len++;}if(dotLen == 3){String[] spilt = queryIP.split("\\.");if(spilt.length == 4){for(int i = 0; i < spilt.length; i++){if(!checkIpv4Segment(spilt[i])){return "Neither";}}return "IPv4";}}if(len == 7){String[] spilt = queryIP.split(":");if(spilt.length == 8){for(int i = 0; i < spilt.length; i++){if(!checkIpv6Segment(spilt[i])){return "Neither";}}return "IPv6";}}return "Neither";}
}