题解 | #验证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(IP.charAt(0) == '.' || IP.charAt(0) == ':' || IP.charAt(IP.length()-1) == '.' || IP.charAt(IP.length()-1) == ':')
        return "Neither";
        if (IP.contains(".")) {
            String[] ip = IP.split("\\.");
            if (ip.length != 4 ) {
                return "Neither";
            } else {

                for (String str : ip) {
                    if (str.length() > 3 || str.charAt(0) == '0') {
                        return "Neither";
                    } else {
                        try{
                        if(Integer.parseInt(str) >= 256){
                            return "Neither";
                        }}catch(Exception e){
                            return "Neither";
                        }
                        for (int i = 0; i < str.length(); i++) {
                            if (str.charAt(i) >= '0' && str.charAt(i) <= '9' ) {
                                continue;
                            } else {
                                return "Neither";
                            }
                        }
                    }
                }
                return "IPv4";
            }
        }

        if (IP.contains(":")) {
            String[] ip6 = IP.split(":");
            if (ip6.length != 8) {
                return "Neither";
            } else {
                int index = -1;
                for (String str : ip6) {
                    if(str.contains("00")){
                        index = str.indexOf("00");
                    }
                    if ((str.contains("00") && (index  == 0) )|| str.length() < 1 || str.length() > 4 || str.isEmpty()) {
                        return "Neither";
                    } else {
                        for (int i = 0; i < str.length(); i++) {
                            if (!(str.charAt(i) >= 'a' && str.charAt(i) <= 'f' || str.charAt(i) >= 'A' && str.charAt(i) <= 'F' || str.charAt(i) >= '0' && str.charAt(i) <= '9')) {
                                return "Neither";
                            }
                        }
                    }
                }
                return "IPv6";


            }

        }
        return "Neither";
    }
}

全部评论

相关推荐

牛客52811839...:电商项目名字改一下,烂大街了
点赞 评论 收藏
分享
lafael:?你认真的?这几个项目已经烂大街到不能再烂了。你变个名字我都认可你好歹有点改进,怎么连名字都不换
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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