题解 | #合法IP#
合法IP
http://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String s = in.next();
boolean flag = false;
//去掉头尾的.
while(s.charAt(0) == '.'){
s = s.substring(1,s.length());
}
while(s.charAt(s.length()-1) == '.'){
s = s.substring(0,s.length()-1);
}
//两个.连续出现的情况
for(int i = 0; i<s.length(); i++){
if(s.charAt(i) == '.' && s.charAt(i+1) == '.'){
flag = true;
System.out.print("NO");
return;
}
}
String[] ss = s.split("\\.");
//判断每一部分是否合法
outer:
for(int i = 0; i<ss.length; i++){
if(ss.length != 4 || (ss[i].charAt(0) == '0' && ss[i].length() != 1)){
flag = true;
break;
}
for(int j = 0; j<ss[i].length(); j++){
if(!Character.isDigit(ss[i].charAt(j)) || ss[i].length()>3 || Integer.valueOf(ss[i])<0 || Integer.valueOf(ss[i])>255){
flag = true;
break outer;
}
}
}
System.out.print(flag?"NO":"YES");
}
}
}