题解 | #合法IP#

合法IP

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

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args)  throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str;

        while ((str = bf.readLine()) != null) {
            String reg =
                " (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
            boolean matches = str.matches(reg);
            if (matches) {
                System.out.println("YES");
            } else {
                String[] split = str.split("\\.");
                if (split.length != 4) {
                    System.out.println("NO");
                    return;
                }
                for (String s : split) {
                    if (s.isEmpty()||s.startsWith("+")) {
                        System.out.println("NO");
                        return;
                    }
                    if (s.startsWith("0") && s.length() >= 2) {
                        System.out.println("NO");
                        return;
                    }
                }
                if (split[0].startsWith("0") && split[0].length() >= 2) {
                    System.out.println("NO");
                    return;
                }
                if (str.startsWith("0.")) {

                    for (int i = 0; i < split.length; i++) {
                        int parseInt = Integer.parseInt(split[i]);
                        if (parseInt < 0 || parseInt > 255) {
                            System.out.println("NO");
                            return;
                        }
                    }
                    System.out.println("YES");
                    return;
                } else if (Integer.parseInt(split[0]) >= 0 &&
                           Integer.parseInt(split[0]) <= 255) {

                    for (int i = 0; i < split.length; i++) {
                        int parseInt = Integer.parseInt(split[i]);
                        if (parseInt < 0 || parseInt > 255) {
                            System.out.println("NO");
                            return;
                        }
                    }
                    System.out.println("YES");
                    return;
                }
                System.out.println("NO");
            }
        }
    }
}

全部评论

相关推荐

八极星:有什么不能问的,(/_\),这又不是多珍贵的机会,你有什么可失去的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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