题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); List<String> stringList = new ArrayList<>(); while (in.hasNext()) { stringList.add(in.next()); } int[] result = new int[7]; stringList.stream().forEach(s -> { String[] str = s.split("~"); if (!checkIpValid(str[0])) { result[5]++; return; } if (str[0].matches("([1-9]|[1-9]\\d|1[0-1]\\d|12[0-6])(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}")) { if (!checkValid(str[1])) { result[5]++; return; } if (str[0].matches("10(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}")) { result[6]++; } result[0]++; } else if(str[0].matches("(12[8-9]|1[3-8]\\d|19[0-1])(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}")) { if (!checkValid(str[1])) { result[5]++; return; } if (str[0].matches("172\\.(1[0-6])|(2\\d)|(3[0-1])(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){2}")) { result[6]++; } result[1]++; } else if(str[0].matches("(19[2-9]|2[0-1]\\d|22[0-3])(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}")) { if (!checkValid(str[1])) { result[5]++; return; } if (str[0].matches("192\\.168(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){2}")) { result[6]++; } result[2]++; } else if(str[0].matches("(22[4-9]|23\\d)(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}")) { if (!checkValid(str[1])) { result[5]++; return; } result[3]++; } else if(str[0].matches("(24\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])){3}")) { if (!checkValid(str[1])) { result[5]++; return; } result[4]++; } }); for (int i : result) { System.out.print(i + " "); } } private static boolean checkIpValid(String s) { String[] strings = s.split("\\."); if (strings.length < 4) { return false; } List<String> stringList = Arrays.asList(strings); if (stringList.contains("")) { return false; } return true; } private static boolean checkValid(String s) { String[] strings = s.split("\\."); if (strings.length < 4) { return false; } List<String> stringList = Arrays.asList(strings); if (stringList.contains("")) { return false; } if (4 == stringList.stream().filter(s1 -> s1.equals("255")).count()) { return false; } if (4 == stringList.stream().filter(s1 -> s1.equals("0")).count()) { return false; } for (int i = 0; i < 4; i++) { if (strings[i].equals("0")) { continue; } if (i != 0 && !strings[i-1].equals("255")) { return false; } int n = Integer.parseInt(strings[i]); for (int j = 7; j >= 0 ; j--) { n -= Math.pow(2,j); if (n == 0) { break; } if (n < 0) { return false; } } } return true; } }