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

密码验证合格程序

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { String pwd = in.nextLine(); if (" ".equals(pwd)) { System.out.println("NG"); continue; } if (pwd.length() <= 8) { System.out.println("NG"); continue; } if (!isWordInvalid(pwd)) { System.out.println("NG"); continue; } // 重复字符串 if (isReply(pwd)) { System.out.println("NG"); continue; } System.out.println("OK");

    }
    in.close();
}

// 字符串中包含1个以上的重复字符串
// 不能有长度大于2的不含公共元素的子串重复
// 这里不可能小8
private static boolean isReply(String pwd) {
    int replyLength = 0;
    char[] pwds = pwd.toCharArray();
    char replyStart;
    int startIndex = 0;
    for (int a = 0; a < pwds.length; a++) {
        replyStart = pwds[a];
        startIndex = a;
        replyLength = 0;
        for (int b = 3 + a; b < pwds.length; b++) { // 从第三位开始找
            if (pwds[startIndex]  == pwds[b]) {
                startIndex++;
                replyLength++;
            } else {
                replyLength = 0;
            }
            if (replyLength > 2) {
                return true;
            }
        }
    }
    return false;
}


// 包括大小写字母.数字.其它符号,以上四种至少三种
private static boolean isWordInvalid(String pwd) {
    int[] types = new int[]{0, 0, 0, 0};
    char[] pwds = pwd.toCharArray();
    for (int a = 0; a < pwds.length; a++) {
        if (typeCount(types) == 3) {
            break;
        }
        if (pwds[a] >= '0' && pwds[a] <= '9') {
            types[0] = 1;
        } else if (pwds[a] >= 'a' && pwds[a] < 'z') {
            types[1] = 1;
        } else  if (pwds[a] >= 'A' && pwds[a] < 'Z') {
            types[2] = 1;
        } else {
            types[3] = 1;
        }
    }
    return typeCount(types) >= 3;
}

private static int typeCount(int[] ts) {
    return ts[0] + ts[1] + ts[2] + ts[3];
}

}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务