题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
import java.util.*;
// 注意类名必须为 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 code = in.next();
//first , we determin the length,then we go the substring part, last, we determin if there have enough type of characters.
if (code.length() <= 8) {
System.out.println("NG");
} else if (!subStringChecker(code)) {
System.out.println("NG");
} else if (!codeChecker(code)) {
System.out.println("NG");
}else{
System.out.println("OK");
}
}
}
//判断字符数量格式是否符合要求。
public static boolean codeChecker(String part) {
//We use hashset to stroe the characters that have appreared,because it helps us automaticlly repove duplicates.
HashSet<String> checker = new HashSet<>();
for (int i = 0; i < part.length(); i++) {
if (Character.isDigit(part.charAt(i))) {
checker.add("Digit");
} else if (Character.isLowerCase(part.charAt(i))) {
checker.add("LowerCase");
} else if (Character.isUpperCase(part.charAt(i))) {
checker.add("UpperCase");
} else {
checker.add("Other");
}
}
return checker.size() >= 3;
}
//we use sliding window to determin if there are repeated sustrings.
public static boolean subStringChecker(String part) {
for (int i = 0; i < part.length() - 2; i++) {
//Be careful, in the code snipped"substring(i,i+n)",the index of i+n is exclude, which means that the substring's elements will be part[i],part[i+1] and part[i+2].
int indicator = part.indexOf(part.substring(i, i + 3), i + 1);
if (indicator != -1) {
return false;
}
}
return true;
}
}
