一、题目

描述
密码要求:
1.长度超过8位
2.包括大小写字母.数字.其它符号,以上四种至少三种
3.不能有相同长度大于2的子串重复
输入描述:
一组或多组长度超过2的字符串。每组占一行
输出描述:
如果符合要求输出:OK,否则输出NG

二、题解

本题难点有两个:

1. 判断字符串类型:大小写字母.数字.其它符号

方法1:使用函数
Character.isDigit() 是否数字
Character.isUpperCase() 是否大写字母
Character.isLowerCase() 是否小写字母
剩下的就是其他符号

方法2:使用ASCII码判断字符类型

if ('A' <= chars[i] && chars[i] <= 'Z') {
    flag[0] = true;
} else if ('a' <= chars[i] && chars[i] <= 'z') {
    flag[1] = true;
} else if ('0' <= chars[i] && chars[i] <= '9') {
    flag[2] = true;
} else {
    flag[3] = true;
}

注意这里使用单引号

2. 不能有相同长度大于2的子串重复

即不能有三个连续的字符(及以上)重复出现,例如:‘zhang’不能重复出现;
主要是理解这句话,实现起来就比较简单了。

两个for循环

boolean sign = true;
for (int i = 0; i < length - 5; i++) {
    for (int j = i + 3; j < length -2; j++) {
        if (line.charAt(i) == line.charAt(j) && line.charAt(i+1) == line.charAt(j+1) && line.charAt(i+2) == line.charAt(j+2)) {
            sign = false;
        }
    }
}

循环条件里的length - 5length - 2是为了防止数组越界

三、java实现

import java.util.Scanner;

/**
 * @author zhangnianlei
 * @description
 * @date 2021/8/3
 */
public class Main {

    private static final String YES = "OK";
    private static final String NO = "NG";

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            // 条件1.
            int length = line.length();
            if (length <= 8) {
                System.out.println(NO);
                continue;
            }

            // 条件2.
            int lowCase = 0;
            int upCase = 0;
            int num = 0;
            int other = 0;
            for (int i = 0; i < length; i++) {
                char c = line.charAt(i);
                if (Character.isLowerCase(c)) {
                    lowCase = 1;
                } else if (Character.isDigit(c)) {
                    num = 1;
                } else if (Character.isUpperCase(c)) {
                    upCase = 1;
                } else {
                    other = 1;
                }
            }

            int count = lowCase + num + upCase + other;
            if (count < 3) {
                System.out.println(NO);
                continue;
            }

            // 条件3.
            boolean sign = true;
            for (int i = 0; i < length - 5; i++) {
                for (int j = i + 3; j < length -2; j++) {
                    if (line.charAt(i) == line.charAt(j) && line.charAt(i+1) == line.charAt(j+1) && line.charAt(i+2) == line.charAt(j+2)) {
                        sign = false;
                    }
                }

            }

            if (sign) {
                System.out.println(YES);
            } else {
                System.out.println(NO);
            }


        }
    }

}