题解 | #密码验证合格程序#

密码验证合格程序

https://www.nowcoder.com/practice/184edec193864f0985ad2684fbc86841

import java.util.Scanner;
import java.util.regex.*;

// 注意类名必须为 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
            System.out.println(checkPwd(in.nextLine()));
        }
    }

    private static String checkPwd(String pwd) {
        if (pwd == null) {
            return "NG";
        }
        if (pwd.length() <= 8) {  // 1、长度要大于8
            return "NG";
        }
        if (pwd.contains(" ") || pwd.contains("\n")) { // 2、不包含空格、空行
            return "NG";
        }
        if (hasRepeatStr(pwd, 0)) { // 3、多次重复
            return "NG";
        }
        int charTypeNum = 0;
        if (Pattern.matches(".*[a-z]+.*", pwd)) {
            charTypeNum++;
        }
        if (Pattern.matches(".*[A-Z]+.*", pwd)) {
            charTypeNum++;
        }
        if (Pattern.matches(".*[0-9]+.*", pwd)) {
            charTypeNum++;
        }
        if (Pattern.matches(".*[\\^$].*", pwd)) {
            charTypeNum++;
        }

        if (Pattern.matches("[^a-zA-Z0-9]", pwd)) {
            charTypeNum++;
        }
        if (charTypeNum < 3) {
            return "NG";
        }
        return "OK";
    }

    private static boolean hasRepeatStr(String pwd, int startIndex) {
        int endIndex = startIndex + 3;
        if (endIndex >= pwd.length()) {
            return false;
        }
        String str = pwd.substring(startIndex, endIndex);
        String lastStr = pwd.substring(endIndex);
        if (lastStr.contains(str)) {
            return true;
        }
        return hasRepeatStr(pwd, startIndex + 1);
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务