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

密码验证合格程序

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

HJ20 密码验证合格程序

1.1 解题思路

  • 长度超过8位:比较字符串长度
  • 包括大小写字母.数字.其它符号,以上四种至少三种:定义一个长度为 4 的数组,上述有一种存在的时候就将对应的数组小标对应的值设置为 1
  • 不能有长度大于2的包含公共元素的子串重复:使用长度为 3 的隔窗进行判断,每次移动一位,移出的部分就是已经判断过的

1.2 实例代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()) {
            System.out.println(passwordOk(sc.nextLine()) ? "OK" : "NG");
        }
    }
    
    public static boolean passwordOk(String str) {
        // 1. 长度限制
        if(str.length() <= 8) {
            return false;
        }
        
        // 2. 符号限制(只能赋初值1,不嫩累加,因为需要的是种类)
        int[] count = new int[4];
        for(int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if(c >= 'a' && c <= 'z') {
                count[0] = 1;
            } else if(c >= 'A' && c <= 'Z') {
                count[1] = 1;
            } else if (c >= '0' && c <= '9') {
                count[2] = 1;          
            } else {
                count[3] = 1;
            }
        }
        
        if(count[0] + count[1] + count[2] + count[3] < 3) {
            return false;
        }
        
        // 2. 公共字串(隔窗法,窗体大小3)
         for(int i = 0; i < str.length() - 3; i++) {
             if (str.substring(i + 3).contains(str.substring(i, i + 3))) {
                 return false;
             }
         }
        return true;
    }
}
全部评论

相关推荐

10-16 15:48
算法工程师
点赞 评论 收藏
分享
Java面试先知:我也是和你一样的情况,hr 说等开奖就行了
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

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