题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
import java.lang.String;
import java.util.Scanner;
import java.util.regex.Pattern;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String s = in.nextLine();
if(s.length()>8 && variousTypes(s) && noDuplication(s,0,3)){//长度超过8位
System.out.println("OK");
}else{
System.out.println("NG");
}
}
}
private static boolean variousTypes(String s){
//包括大小写字母.数字.其它符号,以上四种至少三种
int count = 0;
Pattern p1 = Pattern.compile("[A-Z]");
if(p1.matcher(s).find()){
++count;
}
Pattern p2 = Pattern.compile("[a-z]");
if(p2.matcher(s).find()){
++count;
}
Pattern p3 = Pattern.compile("[0-9]");
if(p3.matcher(s).find()){
++count;
}
Pattern p4 = Pattern.compile("[^a-zA-Z0-9]");
if(p4.matcher(s).find()){
++count;
}
if(count >= 3){
return true;
}
return false;
}
private static boolean noDuplication(String s,int start,int end){
//不能有长度大于2的包含公共元素的子串重复,取长度为3的字符
if(end >= s.length()){
return true;
}
//头尾校验,从头部开始 依次 按照3位长度截取出字符串与剩与长度的字符串进行校验,如果剩余中包含截取的3位字符串则表示出现了重复
if(s.substring(end).contains(s.substring(start,end))){
return false;
}else{
return noDuplication(s,start+1,end+1);
}
}
}
