力扣-字符串-468 检查ip

打印 上一主题 下一主题

主题 1804|帖子 1804|积分 5412

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
思路

观察字符串的使用,另有对所有界限条件的检查
spilt(“\.”),toCharArray,Integer.parseInt()
代码

  1. class Solution {
  2.     boolean checkIpv4Segment(String str){
  3.         if(str.length() == 0 || str.length() > 4) return false;
  4.         if(str.charAt(0) == '0' && str.length() > 1) return false;
  5.         for(char c:str.toCharArray()){
  6.             if(c < '0' || c > '9'){
  7.                 return false;
  8.             }
  9.         }
  10.         int num = Integer.parseInt(str);
  11.         if(num < 0 || num > 255) return false;
  12.         return true;
  13.     }
  14.     boolean checkIpv6Segment(String str){
  15.         for(char c:str.toCharArray()){
  16.             if( (c < '0' ||  c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') ){
  17.                 return false;
  18.             }
  19.         }
  20.         if(str.length() > 4 || str.length() == 0) return false;
  21.         return true;
  22.     }
  23.     public String validIPAddress(String queryIP) {
  24.         int dotLen = 0;
  25.         int len = 0;
  26.         for(int i = 0; i < queryIP.length(); i++){
  27.             if(queryIP.charAt(i) == '.') dotLen++;
  28.             else if(queryIP.charAt(i) == ':') len++;
  29.         }
  30.         if(dotLen == 3){
  31.             String[] spilt = queryIP.split("\\.");
  32.             if(spilt.length == 4){
  33.                 for(int i = 0; i < spilt.length; i++){
  34.                     if(!checkIpv4Segment(spilt[i])){
  35.                         return "Neither";
  36.                     }
  37.                 }
  38.                 return "IPv4";
  39.             }
  40.         }
  41.         if(len == 7){
  42.             String[] spilt = queryIP.split(":");
  43.             if(spilt.length == 8){
  44.                 for(int i = 0; i < spilt.length; i++){
  45.                     if(!checkIpv6Segment(spilt[i])){
  46.                         return "Neither";
  47.                     }
  48.                 }
  49.                 return "IPv6";
  50.             }
  51.         }
  52.         return "Neither";
  53.     }
  54. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

美丽的神话

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表