题解 | #合法IP# 我的代码写的跟shit一样
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
// TMD,普通形式的判断太麻烦了,给我学正则表达式 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()) { // 输入 String ip = in.next(); if (isValid(ip)) { System.out.println("YES"); } else { System.out.println("NO"); } } } public static boolean isValid(String s) { String[] split = s.split("\\."); // 长度为4 if (split.length != 4) { return false; } // 每组字符串转化为数字,不能大于100 try { // for (String str : split) { // // 我认为此时可以考虑异常 // // 考虑首位为0,长度不为1 // if(str.length()>=2&&str.charAt(0)=='0'){ // return false; // } // int i = Integer.parseInt(str); // // 考虑数值范围 // if (i > 255 || i < 0) { // return false; // } // } // 直接遍历每一个字符 for(String str:split){ // 如果是空串,返回错误 if(str.equals("")){ return false; } for(int i=0;i<str.length();i++){ char c=str.charAt(i); if(str.length()>=2&&i==0&&(c>'9'||c<='0')){ return false; } if(c>'9'||c<'0'){ return false; } } int i = Integer.parseInt(str); if(i>255||i<0){ return false; } } } catch (NumberFormatException e) { return false; } return true; } }