题解 | #合法IP#

合法IP

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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String input = in.nextLine();
            String replace = input.replaceAll("\\.", "");
            boolean isNo = false;
            for (int i = 0; i < replace.length(); i++) {
                if (replace.charAt(i) > '9' || replace.charAt(i) < '0') {
                    isNo = true;
                }
            }
            if (!isNo) {
                isNo = defIsNo(input);
            }
            if (isNo) {
                System.out.println("NO");
            } else {
                System.out.println("YES");
            }
        }
    }

    private static boolean defIsNo(String input) {
        String[] array = input.split("\\.", -1);
        if (array.length != 4)
            return true;
        for (String s : array) {
            if (s.isEmpty() || (s.startsWith("0") && s.length() > 1))
                return true;
            int ip = Integer.parseInt(s);
            if (ip < 0 || ip > 255) {
                return true;
            }
        }
        return false;
    }
}

全部评论

相关推荐

球球别再泡了:坏,我单9要了14
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务