题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
思路:ip地址每个字段大小在[0-255]之间,不能有其他字符,不能以0开头
代码如下:
import java.util.*;
import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws IOException {
// Scanner in = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
// 注意 hasNext 和 hasNextLine 的区别
while ((str = br.readLine()) != null) { // 注意 while 处理多个 case
String[] s = str.split("\\.");
if (s.length != 4) {
System.out.println("NO");
continue;
}
boolean isIP = true;
for (int i = 0; i < 4; i++) {
if (s[i].length() <= 0 || s[i].matches(".*[^0-9].*") ||
Integer.parseInt(s[i]) < 0 ||
Integer.parseInt(s[i]) > 255 ||
(s[i].length() > 1 && s[i].charAt(0) == '0')
) {
System.out.println("NO");
isIP = false;
break;
}
}
if (isIP == true) {
System.out.println("YES");
}
}
}
}
