题解 | #合法IP#

合法IP

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

正则表达式匹配就可以了

import java.util.*;
/*

* */
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String[] split = str.split("[.]");
        String ip = "YES";
        if (split.length == 4) {
            for (int i = 0; i < 4; i++) {
            //判断是否以0开头
                boolean matches1 = split[i].matches("^([1-9]\\d\\d*)$");
                if (matches1 == false && split[i].length() != 1) {
                    ip = "NO";
                    break;
                }
                //判断是否符合ip地址
                boolean matches = split[i].matches("^0\\d*$|\\d|[0-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5]");
                if (matches == false) {
                    ip = "NO";
                    break;
                }
            }
        }else
            ip = "NO";
        System.out.println(ip);
    }
}

全部评论

相关推荐

10-14 13:25
已编辑
门头沟学院 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务