感觉用正则表达式比较清晰
import java.util.Scanner;
// 注意类名必须为 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 passWord = in.nextLine();
System.out.println(checkePassWord(passWord) ? "OK" : "NG");
}
}
public static boolean checkePassWord(String str) {
boolean result = false;
if (str.length() <= 8) return result;
boolean isCharUp = false;
boolean isCharLow = false;
boolean isDigit = false;
boolean isOther = false;
int count = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
//System.out.println(c);
if (isCharType(c) == TYPE_DIGIT && !isDigit) {
count = count + 1;
//System.out.println("c" + c + "isCharType(c)" + isCharType(c) + "isDigit" + isDigit);
isDigit = true;
}
if (isCharType(c) == TYPE_CHAR_LOW && !isCharLow) {
count = count + 1;
//System.out.println("c" + c + "isCharType(c)" + isCharType(c) + "isCharLow" + isCharLow);
isCharLow = true;
}
if (isCharType(c) == TYPE_CHAR_UP && !isCharUp) {
count = count + 1;
//System.out.println("c" + c + "isCharType(c)" + isCharType(c) + "isCharUp" + isCharUp);
isCharUp = true;
}
if (isCharType(c) == TYPE_OtHER && !isOther) {
count = count + 1;
// System.out.println("c" + c + "isCharType(c)" + isCharType(c) + "isOther" + isOther);
isOther = true;
}
}
if (count < 3) return false;
for (int i = 0; i < str.length() - 2; i++) {
String shortStr = str.substring(i, i + 3);
String longStr = str.substring(i+3);
if (longStr.contains(shortStr)) {
return false;
}
}
return true;
}
public static int TYPE_DIGIT = 0;
public static int TYPE_CHAR_LOW = 1;
public static int TYPE_CHAR_UP = 2;
public static int TYPE_OtHER = 3;
public static int isCharType(char c) {
if (c >= '0' && c <= '9') {
return TYPE_DIGIT;
}
if (c >= 'a' && c <= 'z') {
return TYPE_CHAR_LOW;
}
if (c >= 'A' && c <= 'Z') {
return TYPE_CHAR_UP;
}
return TYPE_OtHER;
}
}