题解 | 密码验证合格程序
密码验证合格程序
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.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
if ("exit".equalsIgnoreCase(str)) {
break;
}
if (str.trim().isEmpty()) {
continue;
}
if (isRightPwd(str)) {
System.out.println("OK");
} else {
System.out.println("NG");
}
}
in.close();
}
//验证字符串长度是否合法
private static boolean isRightLight(String str) {
return str.length() >= 8;
}
//验证字符串是否含有大写字母
private static boolean isUpCase(String str) {
for (int i = 0; i < str.length(); i++) {
char code = str.charAt(i);
if (Character.isUpperCase(code)) {
return true;
}
}
return false;
}
//验证字符串是否含有小写字母
private static boolean isLowCase(String str) {
for (int i = 0; i < str.length(); i++) {
char code = str.charAt(i);
if (Character.isLowerCase(code)) {
return true;
}
}
return false;
}
//验证字符串是否含有数字
private static boolean isDigit(String str) {
for (int i = 0; i < str.length(); i++) {
char code = str.charAt(i);
if (Character.isDigit(code)) {
return true;
}
}
return false;
}
//验证字符串是否含有特殊字符
private static boolean isSpecial(String str) {
for (int i = 0; i < str.length(); i++) {
char code = str.charAt(i);
if (code >= 33 && code <= 126 && !Character.isLetterOrDigit(code)) {
return true;
}
}
return false;
}
//验证字符串字符种类是否合法
private static boolean isCharacterType(String str) {
int count = 0;
if (isDigit(str)) {
count++;
}
if (isUpCase(str)) {
count++;
}
if (isLowCase(str)) {
count++;
}
if (isSpecial(str)) {
count++;
}
return count >= 3;
}
//验证字符串中是否有不重叠的子串,子串长度>=3
private static boolean isRightString(String str) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < str.length() - 3; i++) {
String sub = str.substring(i, i + 3);
if (map.containsKey(sub)) {
if (i - map.get(sub) >=
3) { //验证是否有重叠,索引差值大于等于3,没有重叠
return false;
}
} else {
map.put(sub, i);
}
}
return true;
}
//验证密码是否合法
private static boolean isRightPwd(String str) {
if (isRightLight(str) && isCharacterType(str) && isRightString(str)) {
return true;
}
return false;
}
}
查看17道真题和解析