题解 | #合法IP#,原来空也算一个长度,额

合法IP

http://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.hasNext()) { // 注意 while 处理多个 case
            String ip = in.nextLine();
            String[] split = ip.split("\\.");
            if (getResult(split)){
                System.out.println("YES");
            }else {
                System.out.println("NO");
            }
        }
    }

    private static boolean getResult(String[] split) {
        if (split.length != 4){
            return false;
        }
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            if (s == null || s.equals("")){
                return false;
            }
            for (int k = 0; k < s.length(); k++) {
                if (!Character.isDigit(s.charAt(k))){
                    return false;
                }
            }
            int j = Integer.parseInt(s);
            if (j < 0 || j > 255){
                return false;
            }
            String substring = s.substring(0, 1);
            if (substring.contains("0") && s.length() != 1){
                return false;
            }

        }
        return true;
    }
}

全部评论

相关推荐

allin秋招的大菠萝很爱交友:后续,已拿offer ~查看图片
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客企业服务