题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
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 s = in.nextLine();
String res = "YES";
String[] ip = s.split("\\.");
if (ip.length != 4) {
res = "NO";
} else {
for (int i = 0; i <= 3; i++) {
if (!ip[i].matches("[0-9]+") ||
(ip[i].charAt(0) == '0' && ip[i].length() >= 2) ||
Integer.parseInt(ip[i]) < 0 ||
Integer.parseInt(ip[i]) > 255) {
res = "NO";
break;
}
}
}
System.out.println(res);
}
}
}
查看8道真题和解析