题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String a;
StringBuffer bu = new StringBuffer();
try {
while ((a = in.readLine()) != null && !a.isEmpty()) {
parse(a, bu);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.print(bu);
}
public static void parse(String a, StringBuffer buffer) {
char[] charAy = a.toCharArray();
int[] subIp = new int[4];
int i = 0, j = 0, n = 0, cnt = 0, l = charAy.length;
boolean illegal = false;
while (i < l) {
if (charAy[i] == '.') {
if (j > 3 || cnt == 0) {//且ip的位数不能为0
illegal = true;
break;
} else {
subIp[j++] = n;//j<4以防数组越界
}
n = 0;
cnt = 0;
} else if ((charAy[i] - '0' | '9' - charAy[i]) > 0) {
if (cnt == 1 &&
n == 0) {//IP是数字,位数大于2,可是第一位是0,仍不是合法IP
illegal = true;
break;
}
n *= 10;
n += charAy[i] - '0';
cnt++;
if (i == l -
1) {//当遍历到输入字符串最后一位时,如果j不是3,表示ip的位数不足或者过多,均不合法
if (j == 3) subIp[j++] = n;
else illegal = true;
}
} else {//不是数字,就不合法
illegal = true;
break;
}
i++;
}
if (illegal || j != 4) buffer.append("NO").append("\n");
else {
i = 0;
while (i < 4) {
if (subIp[i] > 255) {//ip中有位数大于255的,也不是合法IP
illegal = true;
break;
}
i++;
}
if (illegal) buffer.append("NO").append("\n");
else buffer.append("YES").append("\n");
}
}
}
