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

密码验证合格程序

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

关键是第三点:不能有长度大于2的包含公共元素的子串重复

那就要检查3字符的子串,是否有重复的

子串,以第一个字母开头的子串包含了以第二个字母开头的子串。

怎么一个for循环就可以获取子串吗? 至少得一个for获取子串起始位置,一个for获取子串结束位置吧。

其实我们只需要判断,以第一个字母为开始的子串就可以,所以一个for循环获取子串的终止位置就行了。

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

// 注意类名必须为 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
            String str = in.nextLine();

            checkPwd(str);
        }
    }

    public static void checkPwd(String str) {
        if (str.length() <= 8) {
            System.out.println("NG");
            return;
        }

        int upperLetter = 0;
        int lowLetter = 0;
        int num = 0;
        int other = 0;

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isUpperCase(ch)) {
                upperLetter = 1;
            } else if (Character.isLowerCase(ch)) {
                lowLetter = 1;
            } else if (Character.isDigit(ch)) {
                num = 1;
            } else {
                other = 1;
            }
        }

        int sum = upperLetter + lowLetter + num + other;
        if (sum < 3) {
            System.out.println("NG");
            return;
        }

        //不能有长度大于2的包含公共元素的子串重复
        //借助字典减少暴力搜索时间

        //检查3字符的字串,是否有重复的

        //021Abc9Abc1
        Set<String> set = new HashSet<>();

        for (int i = 0; i < str.length() - 2; i++) {
            //substring,左闭右开
            String substr = str.substring(i, i + 3);
            if (!set.contains(substr)) {
                set.add(substr);
            } else {
                System.out.println("NG");
                return;
            }
        }

        System.out.println("OK");
    }
}

#在找工作求抱抱##我的2023新年愿望#
全部评论

相关推荐

评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务