题解 | #合法IP#

合法IP

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

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static final String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String ip = sc.next();
        Matcher matcher = Pattern.compile(regex).matcher(ip);
        if (matcher.matches()) {
            String[] arr = ip.split("\\.");
            for (String s : arr) {
                if (s.length() > 1 && s.startsWith("0")) {
                    System.out.println("NO");
                    return;
                }
                int digit = Integer.parseInt(s);
                if (digit < 0 || digit > 255) {
                    System.out.println("NO");
                    return;
                }
            }
        } else {
            System.out.println("NO");
            return;
        }
        System.out.println("YES");
    }
}

全部评论

相关推荐

06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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