题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
本题只要求判断有没有重复子串,而且是长度大于等于 3 的重复子串,那就只需要判断有没有存在长度等于 3 的重复子串即可,考虑到密码长度不长,用哈希表完全可以接受。
如果要自己实现判别是否存在重复子串的逻辑,判断最长重复子串的长度是否大于 3,难度一下子就上来了。但没必要。
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 pwd = in.next();
boolean isNG = false;
if(pwd.length() <= 8 || pwd.contains("\n") || pwd.contains(" "))
isNG = true;
else{
int count = 0;
if(pwd.matches(".*[a-z].*")) count++;
if(pwd.matches(".*[A-Z].*")) count++;
if(pwd.matches(".*[0-9].*")) count++;
if(pwd.matches(".*[^(a-zA-Z0-9)].*")) count++;
if(count < 3)
isNG = true;
else {
// 直接判断长度为 3 的子串有没有重复就行
Set<String> set = new HashSet<>();
for(int i = 0; i < pwd.length()-3; i++) {
String sub = pwd.substring(i, i+3);
if(set.contains(sub)) {
isNG = true;
break;
}
set.add(sub);
}
}
}
System.out.println(isNG ? "NG" : "OK");
}
}
}

