题解 | #合法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 ipStr = in.nextLine();
            boolean flag = true;
            //先判断格式上是否正确
            if (!ipStr.matches("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}")) {
                System.out.println("NO");
                flag = false;
                return;
            }
            
            String[] ips = ipStr.split("\\.");
            for(int i =0;i<ips.length;i++){
                //如果有0开头的,也是不合法的,排除一下
                if(ips[i].matches("0\\d+")){
                    System.out.println("NO");
                    flag = false;
                    break;
                }

                int temp = Integer.valueOf(ips[i]);
                if(temp < 0||temp>255){
                    System.out.println("NO");
                    flag = false;
                    break;
                }
            }
            if(flag){
                System.out.println("YES");
            }
            
        }
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务