题解 | #验证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
        if(ipv4(IP))
            return "IPv4";
        if(ipv6(IP))
            return "IPv6";

        return "Neither";
    }
    private Boolean ipv6(String IP){
        if(IP.startsWith(":") || IP.endsWith(":")){
            System.out.println("不能根据规则划分");
            return false;
        }
        String[] strs = IP.split(":");
        if(strs.length != 8){
            System.out.println("不能根据规则划分");
            return false;
        }
        
        for(int i = 0; i < strs.length; i++){
            if(strs[i].equals("0")){
                continue;    
            }
            if(strs[i].length() == 0 || strs[i].length() > 4){
                System.out.println("不可省略");
                return false;
            }
            for(int j = 0; j < strs[i].length(); j++){
                if(!legalChar(strs[i].charAt(j))){
                    System.out.println("字符不合法");
                    return false;
                }
            } 
        }
        
        return true;
    }
    private Boolean legalChar(char c){
        if(c <= '9' && c >= '0')
            return true;
        if(c <= 'e' && c >= 'a')
            return true;
        if(c <= 'E' && c >= 'A')
            return true;

        return false;
    }
    private Boolean ipv4(String IP){
        if(IP.startsWith(".") || IP.endsWith(".")){
            System.out.println("不能根据规则划分");
            return false;
        }
        String[] strs = IP.split("\\.");
        if(strs.length != 4){
            System.out.println("不能根据规则划分");
            return false;
        }

        for(int i = 0; i < 4; i++){
            if(strs[i].length() > 1 && strs[i].startsWith("0"))
                return false;
            try{
                int temp = Integer.valueOf(strs[i]);
                if(temp < 0 || temp > 255)
                    return false;
            }catch(Exception e){
                e.printStackTrace();
                System.out.println("报错了");
                return false;
            }
        }

        return true;
    }
}

全部评论
平常的业务就是要写成这样才对,而且还应该自己总结规则,这题考的很有道理
点赞 回复 分享
发布于 2024-06-03 22:02 上海

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务