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

密码验证合格程序

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

使用contains来灵活判断是否有重复子串

import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Pattern;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Main hj = new Main();
        List<String> ress = new ArrayList<>();

        while (in.hasNextLine()) {
            String input = in.nextLine();
            String res = hj.verifyStr(input) ? "OK" : "NG";
            ress.add(res);
        }
        for (String r : ress) {
            System.out.println(r);
        }
    }

    /**
     * 单行校验
     */
  public boolean verifyStr(String str) {
        boolean pass1 = false;
        boolean pass2 = false;

        int length = str.length();
        if (length > 8) {
            pass1 = true;
        } else {
            return pass1;
        }

        int count = 0;
        Pattern p1 = Pattern.compile("[a-z]");
        Pattern p2 = Pattern.compile("[A-Z]");
        Pattern p3 = Pattern.compile("[0-9]");
        Pattern p4 = Pattern.compile("[^a-zA-Z0-9]");

        if (p1.matcher(str).find())
            count++;
        if (p2.matcher(str).find())
            count++;
        if (p3.matcher(str).find())
            count++;
        if (p4.matcher(str).find())
            count++;

        if (count >= 3) {
            pass2 = true;
        } else {
            return pass2;
        }

        boolean pass3 = duplicatedStr(str);

        return pass1 && pass2 && pass3;
    }

    /**
     * 重复子串校验
     */
    public boolean duplicatedStr(String str) {
        String subStr1 = "";
        String subStr2 = "";

        for (int i = 3; i < str.length(); i++) {
            subStr1 = str.substring(i);
            subStr2 = str.substring(i - 3, i);
            if (subStr1.contains(subStr2)) {
                return false;
            }
        }
        return true;
    }

}

全部评论

相关推荐

面试了几家,全程问项目,八股一点都不问,可惜准备了这么久
独角仙梦境:现在感觉问八股像是中场休息一样的,问几个八股放松一下再上强度
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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