题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
这道题要考虑完全属实有些伤脑筋,全靠调试
import java.util.*; public class Solution { /** * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ public String solve (String ip) { // write code here int lg = ip.length(); if(lg<=15){ return checkIPv4(ip)?"IPv4":"Neither"; }else{ return checkIPv6(ip)?"IPv6":"Neither"; } } public boolean checkIPv4(String ip){ String[] str = ip.split("\\."); if(str.length !=4) return false; for(String s : str){ if(!checkNum4(s.toCharArray(),0)||String.valueOf(Integer.valueOf(s)).length()<s.length())return false; } return Integer.valueOf(str[0]) <= 255 && Integer.valueOf(str[1]) <= 255 && Integer.valueOf(str[2]) <= 255 && Integer.valueOf(str[3]) <= 255; } public boolean checkIPv6(String ip){ char[] w= ip.toCharArray(); int count=0; for(char c : w)if(c == ':')count++; if(count>7)return false; String[] str = ip.split(":"); if(str.length !=8) return false; for(String s : str){ if(checkNum6(s.toCharArray(),0)==false||(!s.equals("0")&&s.length()!=4))return false; } return true; } public boolean checkNum6(char[] num,int i){ if(i>=num.length)return true; if(num.length>4 || (Character.isDigit(num[i])==false&&Character.isLetter(num[i])==false))return false; //&& (?(?true:false):(num[i]<='F'?true:false)) if(Character.isLowerCase(num[i]) && num[i] >'f') return false; if(Character.isUpperCase(num[i]) && num[i] > 'F')return false; return (Character.isDigit(num[i])||Character.isLetter(num[i]))&&checkNum6(num,i+1); } public boolean checkNum4(char[] num,int i){ if(i>=num.length)return true; if(num.length>3 || Character.isDigit(num[i])==false)return false; return Character.isDigit(num[i]) && checkNum4(num,i+1); } }