合法IP

描述

IPV4地址可以用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此正号不需要出现),如10.137.17.1,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。

现在需要你用程序来判断IP是否合法。

数据范围:数据组数:1≤t≤18

进阶:时间复杂度:O(n),空间复杂度:O(n)

输入描述:

输入一个ip地址,保证不包含空格

输出描述:

返回判断的结果 YES or NO

示例1

输入:

255.255.255.1000

输出:

NO

Java 编程

package cn.net.javapub.javaintroduction.example;

/**
 * @author: shiyuwang
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while ((str = bf.readLine()) != null) {
            String[] ss = str.split("-");
            if (ss[0].equals("joker JOKER") || ss[1].equals("joker JOKER")) {
                System.out.println("joker JOKER");
                continue;
            }
            String[] str0 = ss[0].split(" ");
            String[] str1 = ss[1].split(" ");
            str0 = findString(str0);
            str1 = findString(str1);
            int len0 = str0.length;
            int len1 = str1.length;

            if (len0 == 4 || len1 == 4) {
                if (len0 == 4 && len1 == 4) {
                    int temp = Integer.parseInt(str0[0]) - Integer.parseInt(str1[0]);
                    if (temp >= 0) {
                        System.out.println(ss[0]);
                        continue;
                    }
                } else if (len0 == 4) {
                    System.out.println(ss[0]);
                    continue;
                } else {
                    System.out.println(ss[1]);
                    continue;
                }

            }

            if (len0 != len1) {
                System.out.println("ERROR");
                continue;
            }

            int temp = Integer.parseInt(str0[0]) - Integer.parseInt(str1[0]);
            if (temp >= 0) {
                System.out.println(ss[0]);
                continue;
            } else {
                System.out.println(ss[1]);
                continue;
            }

        }
    }

    private static String[] findString(String[] str) {
        for (int i = 0; i < str.length; i++) {
            switch (str[i]) {
                case "J":
                    str[i] = "11";
                    break;
                case "Q":
                    str[i] = "12";
                    break;
                case "K":
                    str[i] = "13";
                    break;
                case "A":
                    str[i] = "14";
                    break;
                case "2":
                    str[i] = "15";
                    break;
            }
        }
        return str;
    }
}

展示效果:

华为OD机试 - 合法IP (Java 2024 E卷 100分)_合法IP