题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String str;
while ((str = bf.readLine()) != null) {
String reg =
" (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
boolean matches = str.matches(reg);
if (matches) {
System.out.println("YES");
} else {
String[] split = str.split("\\.");
if (split.length != 4) {
System.out.println("NO");
return;
}
for (String s : split) {
if (s.isEmpty()||s.startsWith("+")) {
System.out.println("NO");
return;
}
if (s.startsWith("0") && s.length() >= 2) {
System.out.println("NO");
return;
}
}
if (split[0].startsWith("0") && split[0].length() >= 2) {
System.out.println("NO");
return;
}
if (str.startsWith("0.")) {
for (int i = 0; i < split.length; i++) {
int parseInt = Integer.parseInt(split[i]);
if (parseInt < 0 || parseInt > 255) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
return;
} else if (Integer.parseInt(split[0]) >= 0 &&
Integer.parseInt(split[0]) <= 255) {
for (int i = 0; i < split.length; i++) {
int parseInt = Integer.parseInt(split[i]);
if (parseInt < 0 || parseInt > 255) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
return;
}
System.out.println("NO");
}
}
}
}
安克创新 Anker公司福利 728人发布