# HJ20 密码验证合格程序

https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841 (opens new window)

# 描述

密码要求:

1.长度超过8位

2.包括大小写字母.数字.其它符号,以上四种至少三种

3.不能有长度大于2的包含公共元素的子串重复 (注:其他符号不含空格或换行)

数据范围:输入的字符串长度满足

输入描述:

一组字符串。

输出描述:

如果符合要求输出:OK,否则输出NG

示例1:

输入:
021Abc9000
021Abc9Abc1
021ABC9000
021$bc9000

输出:
OK
NG
NG
OK

# 解答

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    let line = '';

    while(line = await readline()){
        const isValid = validate(line);

        if (isValid) {
            console.log('OK')
        } else {
            console.log('NG')
        }
    }
}()

function validate(str) {
    return validateLength(str) && validateChars(str) && validateRepeatSubStr(str);
}

function validateLength(str) {
    const len = str.length;

    return len > 8;
}

function validateChars(str) {
    let count = 0;  

    const hasNum = /[0-9]/g.test(str);
    const hasLittleCaseChar = /[a-z]/g.test(str);
    const hasUpperCaseChar = /[A-Z]/g.test(str);
    const hasOtherChar = /[^0-9a-zA-Z \n\r]/g.test(str);

    if (hasNum) {
        count++;
    } 
    if (hasLittleCaseChar) {
        count++;
    }
    if (hasUpperCaseChar) {
        count++;
    }
    if (hasOtherChar) {
        count++;
    }

    return count >= 3;
}

function validateRepeatSubStr(str) {
    let hasRepeatSubStr = false;

    for (let i = 0, len = str.length - 3; i < len; i++) {
        const subStr = str.substring(i, i + 3);
        const lastIndex = str.lastIndexOf(subStr);

        if (i !== lastIndex) {
            hasRepeatSubStr = true;
        }
    }

    return !hasRepeatSubStr;
}
本章目录