题解 | #合法IP#

合法IP

https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String ipAddress = in.nextLine();
            System.out.println(isValidIp(ipAddress) ? "YES" : "NO");
        }
    }


    public static boolean isValidIp(String ipAddress) {
        // 检查IP地址的格式是否包含四个部分
        String[] parts = ipAddress.split("\\.");
        if (parts.length != 4) {
            return false;
        }

        // 检查每个部分是否是0到255之间的整数
        for (String part : parts) {
            if (!part.matches("\\d+")) { // \\d+ 匹配一个或多个数字  
                return false;  
            }  

            // 移除可能的前导零
            String trimmedPart = part.replaceFirst("^0+(?!$)", "");

            // 如果移除前导零后,字符串长度与原字符串长度不同,且原字符串长度大于1,则不合法
            if (!part.equals(trimmedPart) && part.length() > 1) {
                return false;
            }

            // 转换为整数并检查是否在合法范围内
            try {
                int num = Integer.parseInt(part);
                if (num < 0 || num > 255) {
                    return false;
                }
            } catch (NumberFormatException e) {
                // 如果转换失败,则不是有效的数字
                return false;
            }
        }

        // 如果以上检查都通过,则IP地址是合法的
        return true;
    }

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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