题解 | #合法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 sc = new Scanner(System.in);
        String ip = sc.nextLine();
        System.out.println(check(ip) ? "YES" : "NO");
    }

    public static boolean check(String str){
        String[] arr = str.split("\\."); // 必须\\
        int len = arr.length;
        if(len != 4) return false;
        for(int i=0; i<len; i++){
            String s = arr[i];
            if(!check2(s)) return false;
            int num = Integer.parseInt(s);
            // IPv4地址范围:0.0.0.0~255.255.255.255 (约有43亿)
            if(num<0 || num>255){
                return false;
            }
        }
        return true;
    }

    private static boolean check2(String s){
        if("".equals(s) || s.length()==0) return false; //题干说无空格,但可能有空字符
        if(s.length()>=2 && s.charAt(0)=='0') return false; //每段位数多于1时,首位不能为0
        for(int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if(c<'0' || c>'9'){ //判断字符串是否合法
                return false;
            }
        }
        return true;
    }
}

全部评论

相关推荐

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