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

密码验证合格程序

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String passWord = scanner.nextLine();

            System.out.println(passWordIsValid(passWord));
        }
    }
    public static String passWordIsValid(String passWord) {
        // 若密码长度小于等于8 直接返回NG
        if (passWord.length() <= 8){
            return "NG";
        }

        boolean hasBig = false;
        boolean hasSmall = false;
        boolean hasNum = false;
        boolean hasSignal = false;

        char[] array = passWord.toCharArray();
        for (char c : array) {
            // 判断是否有小写字母
            if (c >= 'a' && c <= 'z'){
                hasSmall = true;
            } else if (c >= 'A' && c <= 'Z'){
                hasBig = true;
            } else if ((c - '0') >= 0 && (c - '0') <= 9){
                hasNum = true;
            } else if (c != ' ' && !Character.isWhitespace(c)){
                hasSignal = true;
            }
        }
        // 大小写字母 数字 符号 至少有其三
        int flag = 0;
        if (hasBig){
            flag++;
        }
        if (hasSmall) {
            flag++;
        }
        if (hasNum) {
            flag++;
        }
        if (hasSignal) {
            flag++;
        }
        if (flag < 3){
            return "NG";
        }
        // 判断是否有重复出现的子字符串
        int len = array.length;
        String repeat = "";

        // 长度大于2的子串出现重复 那么出现重复的字符串长度至少为6

        if (len >= 6){
            for (int i = 1; i < len - 1; i++){
                repeat = "" + array[i-1] + array[i] + array[i+1];
                int index1 = passWord.indexOf(repeat);
                int index2 = passWord.lastIndexOf(repeat);
                if (index1 != index2){
                    // 出现相同字符串的第一个位置和最后一个位置不同 字符串有重复
                    return "NG";
                }
            }
        }

        return "OK";
    }
}

全部评论

相关推荐

04-29 22:35
门头沟学院 Java
牛友说改了名字能收到offer:旧图新发查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务