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

密码验证合格程序

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

import java.util.*; 
import java.util.regex.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Set<String> set=new HashSet<>();
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str=in.nextLine();
            int len=str.length();
            if(len<9){
                System.out.println("NG");
                continue;
            }
            if(getMatch(str)){
                System.out.println("NG");
                continue;
            }
            if(getString(str,len,set)){
                System.out.println("NG");
                continue;
            }
            
            System.out.println("OK");
        }
    }

// 使用String中的contains方法进行判断
    public static boolean getString(String str,int l,int r){
        if(r>=str.length()){
            return false;
        }
        if(str.substring(r).contains(str.substring(l,r))){
            return true;
        }else{
            return getString(str,l+1,r+1);
        }
    }
  // 利用散列表增加查询效率
    public static boolean getString(String str,int len,Set<String> set){
        for(int i=0;i<len-2;i++){
            String temp=str.substring(i,i+3);
            if(set.contains(temp)){
                set.clear();
                return true;
            }
            set.add(temp);
            //System.out.println(temp);
        }
        set.clear();
        return false;
    }

    public static boolean getMatch(String str){
        int count=0;
        Pattern p1=Pattern.compile("[A-Z]");
        if(p1.matcher(str).find()){
            count++;
        }
        Pattern p2=Pattern.compile("[a-z]");
        if(p2.matcher(str).find()){
            count++;
        }
        Pattern p3=Pattern.compile("[0-9]");
        if(p3.matcher(str).find()){
            count++;
        }
        Pattern p4=Pattern.compile("[^A-Za-z0-9]");
        if(p4.matcher(str).find()){
            count++;
        }
        if(count>=3){
            return false;
        }
        return true;
    }

    
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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