题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str;
while (in.hasNext()) {
str = in.next();
//重点,该输出NG的情况要包含完,各种情况符合都为NG,走遍了之后没有输出ng,最后就是OK
// 检查长度是否超过8位
if (str.length() <= 8) {
System.out.println("NG");
continue;
}
// 检查是否包括大小写字母、数字、其它符号中的至少三种
int countTypes = 0;
if (str.matches(".*[0-9].*")) countTypes++;
if (str.matches(".*[a-z].*")) countTypes++;
if (str.matches(".*[A-Z].*")) countTypes++;
if (str.matches(".*[^a-zA-Z0-9 ].*")) countTypes++; // 包括其他符号
if (countTypes < 3) {
System.out.println("NG");
continue;
}
// 检查是否有长度大于2的公共子串重复
boolean hasRepeatingSubstring = hasRepeatingSubstring(str, 3);
if (hasRepeatingSubstring) {
System.out.println("NG");
continue;
}
// 如果所有检查都通过,则输出"OK"
System.out.println("OK");
}
in.close();
}
// 辅助方法,检查字符串是否有长度大于等于指定长度的重复子串
private static boolean hasRepeatingSubstring(String str, int minLength) {
int len = str.length();
//012012012
for (int i = 0; i < len - minLength; i++) {//0-2
for (int j = i + minLength; j <= len-minLength; j++) {//0-2
//这两种if判断都通过了,不过底下的可以少判断几次【substring(1,4)即取得1,2,3】
// if (str.substring(i, i + minLength).equals(str.substring(j - minLength+1, j+1 ))) {
if (str.substring(i, i + minLength).equals(str.substring(j , j+minLength ))) {
//0,2 ---1,0【】j+minlength
return true;
}
}
}
return false;
}
}
查看30道真题和解析

