题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while((input = reader.readLine()) != null){
if(input.length() > 8 && hasThreeValidChars(input) && noRepeat(input)){
System.out.println("OK");
} else {
System.out.println("NG");
}
}
}
// 判断是否有超过三个有效字符
public static boolean hasThreeValidChars(String str){
int[] validChars = new int[4];
for(Character ch : str.toCharArray()){
if(Character.isLetter(ch)){
if(ch >= 65 && ch <= 90){
validChars[0] = 1;
} else if(ch >= 97 && ch <= 122){
validChars[1] = 1;
}
}else if(Character.isDigit(ch)){
validChars[2] = 1;
} else {
validChars[3] = 1;
}
}
int count = 0;
for(int i : validChars){
count += i;
}
return count >= 3;
}
// 判断是否有长度大于2的重复子字符串
public static boolean noRepeat(String str){
/**
* 思路是从前往后依次遍历长度为3的子字符串,看看lastIndexOf是否大于当前索引
*/
for(int i = 0; i < str.length() - 2; i++){
String compare = str.substring(i, i + 3);
if(str.lastIndexOf(compare) > i){
return false;
}
}
return true;
}
}
查看13道真题和解析
