描述
密码要求:
1.长度超过8位
2.包括大小写字母.数字.其它符号,以上四种至少三种
3.不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)
数据范围:输入的字符串长度满足 1≤n≤100 1≤n≤100
输入描述:
一组字符串。
输出描述:
如果符合要求输出:OK,否则输出NG
示例1
输入:
021Abc9000 021Abc9Abc1 021ABC9000 021$bc9000
输出:
OK NG NG OK
题解
import java.util.Scanner;
import java.util.ArrayList;
// 注意类名必须为 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
//1.长度超过8位
//2.包括大小写字母.数字.其它符号,以上四种至少三种
//3.不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)
String str = in.nextLine();
// 验证密码
boolean res = getRes(str);
if (res) {
System.out.println("OK");
} else {
System.out.println("NG");
}
}
}
public static boolean getRes(String str) {
// 判断 长度 是否合格
if (str.length() > 8) {
// 判断符号是否合格
int a = 0; //大写字母
int b = 0; //小写字母
int c = 0; //数字
int d = 0; //其他字符
for (int i = 0; i < str.length(); i++) {
char ch = (char)str.charAt(i);
if (Character.isDigit(ch)) {
c = 1;
} else if (Character.isLowerCase(ch)) {
b = 1;
} else if (Character.isUpperCase(ch)) {
a = 1;
} else {
d = 1;
}
}
if ((a + b + c + d) >= 3) {
//判断子串重复
if (repeat(str)) {
return true;
}
}
}
return false;
}
public static boolean repeat(String str) {
// 所有长度为3的子串不能重复
ArrayList<String> s = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
if (i + 3 > str.length()) {
continue;
}
String s1 = str.substring(i, i + 3);
s.add(s1);
}
for (int i = 0; i < s.size(); i++) {
for (int j = 0; j < s.size(); j++) {
if (i == j) {
continue;
}
if (s.get(i).equals(s.get(j))) {
return false;
}
}
}
return true;
}
}