首页 > 试题广场 >

合法IP

[编程题]合法IP
  • 热度指数:244772 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

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

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

数据范围:数据组数:
进阶:时间复杂度:,空间复杂度:



输入描述:

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



输出描述:

返回判断的结果YES or NO

示例1

输入

255.255.255.1000

输出

NO
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s1 = in.nextLine();
        String result = "YES";
        String s2="";
        try {
            int[] ip = Arrays.stream(s1.split("\\.")).mapToInt(Integer::parseInt).toArray();


            for (int i = 0; i < ip.length; i++) {
                s2=s2+ip[i]+".";
                if (!(ip[i] >= 0 && ip[i] <= 255)) {
                    result = "NO";
                }
            }
            if (ip.length != 4) {
                result = "NO";
            }
         if(!s2.substring(0, s2.length()-1).equals(s1)){
            result = "NO";
        }
        }catch (Exception e){
            result = "NO";
        }
       
       
        System.out.println(result);
    }
}
1.2.3.4 字符串拆分成数字数组
如果不能成功转换成0-255的数字,返回NO
如果数组长度不等于4,返回NO
01.2.3.4转成数字数组再拼接等于1.2.3.4,不匹配,返回NO
发表于 2024-03-28 14:02:33 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String [] arr = in.nextLine().split("\\.");
        String result = "YES";
        if (arr.length != 4) {
            result = "NO";
        }
        for (int i = 0; i < arr.length; i++) {
            if(arr[i].length() == 0  || !arr[i].matches("(0|[1-9]\\d*)")){
                result = "NO";
                break;
            }
            Integer n = Integer.parseInt(arr[i]);
            if ( n < 0 || n > 255) {
                result = "NO";
            }
        }
        System.out.println(result);
    }
}

发表于 2023-11-28 14:58:29 回复(0)
    public static boolean checkIP(String str) {
        String[] strs = str.split("\\.");
        if (strs.length != 4) {
            return false;
        }
        for (String s : strs) {
            if (!s.matches("^(0|[1-9]\\d*)$"))
                return false;
            int val = Integer.valueOf(s);

            if (val > 255 || val < 0) {
                return false;
            }
        }
        return true;
    }

发表于 2023-10-15 21:47:02 回复(0)
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 a = in.nextLine();
            String[] IPs = a.split("\\.");

            // 1-保证分成了四部分
            if(IPs.length != 4) {
                System.out.println("NO");
                return;
            }
            
            for(int i = 0; i < 4; i++) {
                // 2-四部分中没有为空的部分
                if("".equals(IPs[i]) || IPs[i] == null) {
                    System.out.println("NO");
                    return;
                }

                // 3-不为空要保证每个字符都是数字组成的
                for(int j = 0; j < IPs[i].length(); j++) {
                    if(IPs[i].charAt(j) < '0' || IPs[i].charAt(j) > '9') {
                        System.out.println("NO");
                        return;
                    }
                }

                int ip = Integer.parseInt(IPs[i]);

                // 4-数字在不为0的时候不能用0开头
                if('0' == IPs[i].charAt(0) && ip != 0) {
                    System.out.println("NO");
                    return;
                }

                // 5-保证合法的数字范围
                if(ip < 0 || ip > 255) {
                    System.out.println("NO");
                    return;
                }
            }

            System.out.println("YES");
        }
    }
}

发表于 2023-08-16 09:53:25 回复(0)
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;

        while ((line = br.readLine()) != null) {
            System.out.println(checkIP(line));;
        }
    }

    /**
     * 判断ip地址是否合法
     * @param line
     * @return
     */
    private static String checkIP(String line) {
        String[] split = line.split("\\.");
        // 长度不为4的不合法
        if (split.length != 4) {
            return "NO";
        }
        
        for (int i = 0; i < split.length; i++) {
            try {
                int num = Integer.parseInt(split[i]);
                // 大于255的不合法
                if (num > 255) {
                    return "NO";
                }
                
                // 如果以0开头,但不等于0的,不合法
                if (split[i].startsWith("0") && num != 0){
                    return "NO";
                }
                
                // 带符号的不合法
                if (split[i].startsWith("+") || split[i].startsWith("-")){
                    return "NO";
                }
            } catch (NumberFormatException e) {
                // 转换为数字异常的不合法
                return "NO";
            }
        }

        return "YES";
    }
}

发表于 2023-08-14 10:51:45 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String[] strs = sc.nextLine().split("\\.");
            String jg="YES";
            if(strs.length==4){
                for(String s:strs){
                    if(s.length()==0){
                        jg="NO";
                        break;
                    }
                    for(Character ch:s.toCharArray()){
                        if(!Character.isDigit(ch)){
                            jg="NO";
                            break;
                        }
                    }
                    if(s.length()!=1&&s.charAt(0)=='0'){
                        jg="NO";
                        break;
                    }
                    if(Integer.parseInt(s)>255){
                        jg="NO";
                        break;
                    }
                }
            }else{
                jg="NO";
            }
            System.out.println(jg);
        }
    }
}

发表于 2023-07-20 18:47:41 回复(0)
 public static boolean isIp(String ip){
        String[] strs = ip.split("\\.");
        if(strs.length!=4){
            return false;
        }
        for(int i=0;i<strs.length;i++){
            String str = strs[i];
            if(str.isEmpty()){
                return false;
            }
            if(!str.matches("[0-9]+")){
                return false;
            }
            int strInt = Integer.parseInt(str);
            if(strInt<0 || strInt>255){
                return false;
            }
            if(str.startsWith("0")&&strInt!=0){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.next();
            boolean flag = isIp(a);
            System.out.println(flag==true?"YES":"NO");
        }
    }
发表于 2023-04-19 19:42:53 回复(0)
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
            boolean flag = true;
            String[] parts = in.next().split("\\.");
            if (parts.length != 4) {
                flag = false;
            } else {
                for (String s : parts) {
                    if ("".equals(s) || s.matches("^[+-].*") || s.matches("^0\\d+") || Integer.parseInt(s) > 255) {
                        flag = false;
                        break;
                    }
                }
            }
            System.out.println(flag ? "YES" : "NO");
        }
    }
}

发表于 2023-03-10 22:24:16 回复(0)
public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  String str = br.readLine();  String[] strs = str.split("\\.");  String result = "YES";  if( strs.length == 4) { for (int i = 0; i < strs.length; i++) {
            String s = strs[i];  //确保每个位置上有值  if (s.length()<1) {
                result = "NO";break;  } //确保每个段位是数字类型  if (!isNumber(s)) {
                result = "NO";break;  } //确保每个段位的值不大于255  if (Integer.parseInt(s) > 255) {
                result = "NO";break;  } //确保每个段位两位数以上时,不是以0开头  if (s.length() > 1 && s.startsWith("0")) {
                result = "NO";break;  }
        }
    }else {
        result = "NO";  }
    System.out.println(result);  } private static boolean isNumber(String s) { for (int i = 0; i < s.length(); i++) { if (!Character.isDigit(s.charAt(i))) { return false;  }
    } return true; }
发表于 2022-09-01 15:16:02 回复(0)
暴力破解
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while((line = br.readLine()) != null){
            System.out.println(isValidate(line));
        }
    }
    public static String isValidate(String line){
        String[] IPArr = line.split("\\.");
        int temp = 0;
        if(IPArr.length != 4){  // IPV4必须分为4个数组
            return "NO";
        }
        for(int i = 0; i < 4; i++){
            if(IPArr[i] == null || IPArr[i].length() == 0){ // 分组后的每一个数不能为null或者""
                return "NO";
            }
            temp = Integer.parseInt(IPArr[i]);
            if(!IPArr[i].equals(temp + "")){  // 排除以0开头的数
                return "NO";
            }
            if(temp < 0 || temp > 255){
                return "NO";
            }
        }
        return "YES";
    }
}


发表于 2022-08-17 10:04:04 回复(0)
运行时间:14ms超过92.57% 用Java提交的代码
占用内存:9492KB超过100.00%用Java提交的代码
错了六次终于过了,一开始考虑的不全面,比如"1.2.3", "1.2.3.", "1.2.3.4.5" "01.1.2.3", "+1.2.3.4", "0.1.2.3", "1.2..3", ".1.2.3"这些测试用例。感觉直接遍历要比用字符串处理函数split要好。
用了很多判断函数,如果碰到点字符'.'判断一下已读取的数字是不是空的或者点字符是不是在末尾,再判断字符是不是非数字,再判断这个数字字符是不是前缀0,再判断读取的数字是不是大于255,最后判断点字符个数是不是3个。
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String ip = br.readLine();
        int len = ip.length();
        int counts = 0, cur = 0;
        boolean isValid = true, isEmpty = true;
        for (int i = 0; i < len; i++) {
            char ch = ip.charAt(i);
            if (ch == '.') {
                if (isEmpty || i == len - 1) {
                    isValid = false;
                    break;
                }
                isEmpty = true;
                counts++;
                cur = 0;
                continue;
            }

            if (!Character.isDigit(ch)) {
                isValid = false;
                break;
            }

            int num = ch - '0';
            if (cur == 0 && num == 0 && i != len - 1 && ip.charAt(i + 1) != '.') {
                isValid = false;
                break;
            }

            isEmpty = false;
            cur = cur * 10 + num;
            if (cur > 255) {
                isValid = false;
                break;
            }
        }
        isValid = counts == 3 && isValid;

        System.out.println(isValid ? "YES" : "NO");
    }
}


发表于 2022-08-12 12:14:24 回复(1)
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        if (str.contains("+")||str.contains("-")){
            System.out.println("NO");
            return;
        }
        String[] strArray = str.split("\\.");
        for (String s : strArray) {
            if (s.equals("") || (s.charAt(0) == '0' && s.length()>1) || Integer.parseInt(s) > 255 || strArray.length != 4 || Integer.parseInt(s) < 0) {
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
    }
}

发表于 2022-08-03 17:35:33 回复(2)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        String[] strArray = str.split("\\.");
        if (str.contains("+")||str.contains("-")){
            System.out.println("NO");
            return;
        }
        for (String s : strArray) {
            if (s.equals("") || (s.charAt(0) == '0'&&s.length()>1) || Integer.parseInt(s) > 255 || strArray.length != 4 || Integer.parseInt(s) < 0) {
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
    }
}

发表于 2022-08-02 01:56:21 回复(0)
考这个有什么意义呢?
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String[] split = line.split("\\.");
        //必须是四部分
        if (split.length != 4){
            System.out.println("NO");
            return;
        }
        boolean legal = true;
        for (int i = 0; i < split.length; i++) {
            String numstr = split[i];
            //每部分不能为空
            if (numstr == null || "".equals(numstr)){
                legal = false;
                break;
            }
            //每部分必须全是数字
            char[] chars = numstr.toCharArray();
            boolean numic = true;
            for (int j = 0; j < chars.length; j++) {
                if (!getNumic(chars[j])) {
                    numic = false;
                    break;
                }
            }
            if (!numic) {
                legal = false;
                break;
            }
            //数字不能太长,太长转换int类型会报错
            if (numstr.length() > 3) {
                legal = false;
                break;
            }
            //数字不能超过255
            Integer num = Integer.valueOf(numstr);
            if (num > 255) {
                legal = false;
                break;
            }
            //首位是否是有效数字,针对 099.255.255.255
            String strcopy = String.valueOf(num);
            if (!strcopy.equals(numstr)){
                legal = false;
                break;
            }
        }

        System.out.println(legal ? "YES" : "NO");
    }

    //校验是否是数字
    public static boolean getNumic(char c) {
        if (c >= '0' && c <= '9') {
            return true;
        } else {
            return false;
        }
    }


发表于 2022-07-05 16:19:56 回复(0)
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader   br =  new BufferedReader(new InputStreamReader(System.in));
        String intput = br.readLine();
        //校验点一:有三个点;
        //校验点二:取值都是数字且大于0小于256
        //存在坑有点多  注意:+1.2.3.8,.2.3.8  0.2.3.8
        boolean flag = true;
        String[] input = intput.split("\\.");
        int len = input.length;
        if (len != 4) {
            flag = false;

            System.out.print("NO");
            return;

        }
        for (String str : input) {
            if (str.isEmpty() || (str.length() > 1 && (str.charAt(0) < '1' ||
                                  str.charAt(0) > '9'))) {
                flag = false;
                break;
            }
            try {
                int ip = Integer.parseInt(str);

                if (0 <= ip && ip < 256) {
                    flag = true;
                } else {

                    flag = false;
                    break;
                }
            } catch (Exception e) {

                flag = false;
                break;
            }
        }
        if (flag) {
            System.out.print("YES");
        } else {
            System.out.print("NO");
        }


    }
}
发表于 2022-06-29 15:39:31 回复(0)
import java.util.*;
public class Main{
    public static boolean isTrue(String[] strs){
        if(strs.length != 4){
            return false;
        }
        for(int i=0;i<strs.length;i++){
            for(int j=0;j<strs[i].length();j++){
                if(!Character.isDigit(strs[i].charAt(j))){
                    return false;
                }
            }
            if(strs[i]==null || strs[i].length()==0){
                return false;
            }
            if(strs[i].startsWith("0") && Integer.valueOf(strs[i])!=0){
                return false;
            }
            if(Integer.valueOf(strs[i])<0 || Integer.valueOf(strs[i])>255){
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.next();
            String[] strs = str.split("\\.");
            String res = isTrue(strs)? "YES":"NO";
            System.out.println(res);
        }
    }
}

发表于 2022-06-26 21:56:41 回复(0)
import java.util.*;
public class Main{
     public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
       String str = in.nextLine();
        System.out.println(istrue(str));

    }
    public static String istrue(String str) {
        String[] strs = str.split("\\.");
        for (String s : strs) {
            if ((s.length() > 1 && !s.substring(0, 1).matches("[1-9]"))) {
                return "NO";
            } else {
                if (!(strs.length == 4 && !s.isEmpty() && Integer.parseInt(s) >= 0 && Integer.parseInt(s) <= 255)) {
                    return "NO";
                }
            }
        }
        return "YES";
    }
}
发表于 2022-05-24 00:22:49 回复(1)
import java.util.*;

public class Main {
 
    // 解法,单次遍历字符换,根据每个字符进行检测
    // 时间复杂度O(n),空间复杂度O(1)
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String scIn = sc.nextLine();
            int ip = -1;
            int checkCount = 0;
            for (char c : scIn.toCharArray()) {
                if (c >= '0' && c <= '9') {
                    // 刚开始检测到ip值,默认是-1,如果检测到第一个是0,下一个还是0则直接为NO
                    if (ip == 0) {
                        System.out.println("NO");
                        return;
                    }
                    if (ip == -1) ip = 0; // 首次检测到,先将ip赋予0,即从个位数开始计算
                    ip = ip * 10 + c - 48; // 检测ip公式,ip = ip * 10 + c - 48;
                } else {
                    // 当首个字符为'.',或者连续两个字符'.' 则ip不合法,返回NO
                    if (ip == -1) {
                        System.out.println("NO");
                        return;
                    }
                    checkCount++; // 检测到'.' 计数
                    ip = -1; // 恢复ip默认值,便于下个一值检测
                }
                // 当ip值超过255,则不合法
                if (ip > 255) {
                    System.out.println("NO");
                    return;
                }
            }
            // 检测完成后,判断'.'个数不超过3个和最后个字符为'.'则不合法
            if (checkCount != 3 || ip == -1) {
                System.out.println("NO");
            } else {
              System.out.println("YES");  
            }
        }
    }
}
发表于 2022-05-14 12:13:47 回复(0)