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

密码验证合格程序

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

import java.util.Scanner;

import java.util.regex.Pattern;
import java.util.regex.Matcher;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String bigLeReg = "[A-Z]";
        String lowLeReg = "[a-z]";
        String numReg = "[0-9]";
        String otherReg = "[^0-9a-zA-Z\\s\\r\\n]";
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            if(str == null || str.length() < 8 || str.length() > 100) {
                System.out.println("NG");
                continue;
            }
            int i = 0;
            Pattern pat = Pattern.compile(bigLeReg);
            Matcher mt = pat.matcher(str);
            if(mt.find()) {
                i++;
            }
            pat = Pattern.compile(lowLeReg);
            mt = pat.matcher(str);
            if(mt.find()) {
                i++;
            }
            pat = Pattern.compile(numReg);
            mt = pat.matcher(str);
            if(mt.find()) {
                i++;
            }

            pat = Pattern.compile(otherReg);
            mt = pat.matcher(str);
            if(mt.find()) {
                i++;
            }
            if(i < 3) {
                System.out.println("NG");
                continue;
            } 

            if(!checkRepeat(str,0,3)) {
                System.out.println("NG");
                continue;
            }
            
            System.out.println("OK");
            
        }
    }

    //不能有长度大于2的不含公共元素的子串重复 (注:其他符号不含空格或换行)
    private static boolean checkRepeat(String str,int start,int end){
        //题解长度不超2的字符串则采用长度为3的字符,若等于str则表示当前str不包含重复的
        if(end>=str.length()){
            return true;
        }
        //头尾校验,从头部开始 依次 按照3位长度截取出字符串与剩与长度的字符串进行校验,如果剩余中包含截取的3位字符串则表示出现了重复
        if(str.substring(end).contains(str.substring(start,end)))
            return false;
        else
           return checkRepeat(str,start+1,end+1);
         
    }
}

全部评论

相关推荐

投递华为等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务