题解 | 合法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);
String str = in.nextLine();
String[] strs = str.split("\\.");
boolean result = true;
// 长度必须是4
if (strs.length != 4) {
System.out.println("NO");
return;
}
for (String s : strs) {
// 不能是 + 和 - 开头
if(s.startsWith("+") || s.startsWith("-")) {
result = false;
break;
}
// 长度大于1不能是0开头
if(s.length() > 1 && s.startsWith("0")) {
result = false;
break;
}
try {
// 转换成数据不能大于255
if (Integer.parseInt(s) > 255) {
result = false;
break;
}
} catch (Exception e) {
result = false;
break;
}
}
if (result) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}