题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
import java.util.Scanner; //自己做了知道为什么通过率这么低了,各种条件要是没有用例,真是容易遗漏条件的 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(); System.out.println(isVaild(a)); } in.close(); } private static String isVaild(String str) { char[] ac = str.toCharArray(); for(char c : ac){ if(!Character.isDigit(c) && c!='.'){ return "NO"; } } String[] arr = str.split("\\."); if (arr.length != 4) { return "NO"; } for (int i = 0; i < arr.length; i++) { int a = 0; try { if (arr[i].equals(null)) { return "NO"; } else if (arr[i].length()>1 && arr[i].charAt(0) == '0') { return "NO"; } a = Integer.parseInt(arr[i]); } catch (Exception e) { return "NO"; } if (a < 0 || a > 255) { return "NO"; } } return "YES"; } }