【JavaScript】华为机试_HJ20_密码验证合格程序

题目描述

你需要书写一个程序验证给定的密码是否合格。

合格的密码要求:

(1)长度不少于8位

(2)必须包含大写字母、小写字母、数字、特殊字符中的至少三种

(3)不能分割出两个独立的、长度大于2的连续子串,使得这两个子串完全相同

题目链接:https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841?tpId=37\&tqId=21243\&rp=1\&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37\&difficulty=undefined\&judgeStatus=undefined\&tags=\&title=

解答

第一次通过示例

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

void async function () {
    // Write your code here
    while(line = await readline()){
        let res = "OK";
        let count = 0;
        if (line.length < 8) {
            console.log("NG");
            continue;
        }
        count = line.match(/[A-Z]/) ? ++count : count;
        count = line.match(/[a-z]/) ? ++count : count;
        count = line.match(/[0-9]/) ? ++count : count;
        count = line.match(/[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]/) ? ++count : count;
        if (count < 3) {
            console.log("NG");
            continue;
        }
        for (let i = 0; i < line.length - 5; i++) {
            let substr = line.slice(i, i+3);
            if (i > 0 && line.slice(0, i).includes(substr)) {
                res = "NG";
                break;
            } else if (i+3 < line.length && line.slice(i+3).includes(substr)) {
                res = "NG";
                break;
            }
        }
        console.log(res);
    }
}()

优化

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

void async function () {
    // Write your code here
    while(line = await readline()){
        if (isPassword(line)) {
            console.log("OK");
        } else {
            console.log("NG");
        }
    }
}()

function isPassword (pwd) {
    if (!pwd || pwd.length < 8) return false;

    let matchCount = 0;
    const regs = [/\d/g, /[A-Z]/g, /[a-z]/g, /\W/g];
    regs.forEach( reg => matchCount = reg.test(pwd) ? ++matchCount : matchCount);
    if (matchCount < 3) return false;
    
    for (let i = 0; i < pwd.length - 5; i++) {
        const substr = pwd.slice(i, i+3);
        if (pwd.slice(i+3).includes(substr)) return false;
    }
    return true;
}
相关推荐
肖恭伟2 小时前
Cursor Superpowers 零基础开发 Qt 界面
开发语言·qt
liuyao_xianhui2 小时前
优选算法_分治_快速排序_归并排序_C++
开发语言·数据结构·c++·算法·leetcode·排序算法·动态规划
qq_283720052 小时前
Qt QML 中为 CheckBox 设置鸿蒙字体(HarmonyOS Sans)——适配 Qt 5.6.x 与 Qt 5.12+
开发语言·qt·harmonyos
未知鱼2 小时前
Python安全开发之简易目录扫描器(含详细注释)
开发语言·python·安全
左左右右左右摇晃2 小时前
Java并发——死锁
java·开发语言·spring
小白橘颂2 小时前
【C语言】基础概念梳理(一)
c语言·开发语言·stm32·单片机·mcu·物联网·51单片机
沫离痕2 小时前
AI机器人客服-Dify接入
开发语言·javascript·ecmascript
半瓶榴莲奶^_^3 小时前
java模式
java·开发语言
sword devil9003 小时前
TRAE:agent团队
开发语言