题解 | #密码验证合格程序#
密码验证合格程序
https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String str = in.nextLine();
if (str.length() <= 8) {
System.out.println("NG");
} else {
if (getMatches(str)) {
if (isReapte(str)) {
System.out.println("OK");
} else {
System.out.println("NG");
}
} else {
System.out.println("NG");
}
}
}
}
public static boolean getMatches(String str) {
int count = 0;
//这里注意这里不能直接写[A-Z]
if (str.matches(".*[A-Z].*")) {
count++;
}
if (str.matches(".*[a-z].*")) {
count++;
}
if (str.matches(".*[0-9].*")) {
count++;
}
//[^0-9]表示除0-9外的其他字符
if (str.matches(".*[^a-zA-Z0-9].*")) {
count++;
}
if (count >= 3) {
return true;
} else {
return false;
}
}
//补充一点,一开始只考虑了字符串长度为3的重复,但是后面了解到重复长度为4、5的必定会有长度为3的重复,算是 歪打正着
public static boolean isReapte(String str) {
Map<String, String> map = new HashMap<String, String>();
for (int i = 3; i <= str.length(); i++) {
//这里注意substring方法不包含最后一位
String tempStr = str.substring(i - 3, i);
if ("1".equals(map.get(tempStr))) {
return false;
} else {
map.put(tempStr, "1");
}
}
return true;
}
}
注意substring方法不包含最后一位,以及matches方法的使用
