天天看點

華為筆試算法題:密碼要求

題目描述

密碼要求:

1.長度超過8位

2.包括大小寫字母.數字.其它符号,以上四種至少三種

3.不能有相同長度大于2的子串重複

輸入描述:

一組或多組長度超過2的子符串。每組占一行

輸出描述:

如果符合要求輸出:OK,否則輸出NG

方法一(分割字元串)
import java.util.Scanner;

public class Main {
    // 1.長度超過8位
    public static boolean checkLength(String password){
        if (password == null || password.length() <= 8)
            return false;
        return true;
    }
    // 2.包括大小寫字母.數字.其它符号,以上四種至少三種
    public static boolean checkCharKinds(String password){
        int Digit = 0, lowercase = 0, uppercase = 0, others = 0;
        char[] ch = password.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (ch[i] >= '0' && ch[i] <= '9') {
                Digit = 1;
            }
            else if (ch[i] >= 'a'&&ch[i] <= 'z') {
                lowercase=1;
            }
            else if (ch[i] >= 'A' && ch[i] <= 'Z') {
                uppercase=1;
            }else {
                others=1;
            }
            if(Digit + lowercase + uppercase + others == 3)
                return true;
        }
        return false;
    }
    // 3.不能有相同長度超2的子串重複
    public static boolean checkCharRepeat(String password){
        for(int i = 0 ;i < password.length() - 2 ;i ++){
            String substr1 = password.substring(i, i + 3);
            if (password.substring(i + 1).contains(substr1))
                return false;
        }
        return true;
    }
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        while (cin.hasNextLine()) {
            String psw = cin.nextLine();
            if (checkLength(psw) && checkCharKinds(psw) && checkCharRepeat(psw))
                System.out.println("OK");
            else
                System.out.println("NG");
        }
    }
}
           
方法二(正規表達式)
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String pwd = in.nextLine();
            // 長度check, 相同長度超2的子串重複check
            if (pwd.length() <= 8 || pwd.replaceAll("(.{3,})(?=.{3,}\\1)", "").length() < pwd.length()) {
                System.out.println("NG");
                continue;
            }
            // 大小寫字母.數字.其它符号check
            int count = 0;
            if (pwd.matches(".*\\d+.*")) count++;
            if (pwd.matches(".*[a-z]+.*")) count++;
            if (pwd.matches(".*[A-Z]+.*")) count++;
            if (pwd.matches(".*[\\p{P}\\p{S}]+.*")) count++;
            if (count < 3) {
                System.out.println("NG");
                continue;
            }
            System.out.println("OK");
        }
        in.close();
    }
}
           
運作結果:

第一種方式在時間和空間複雜度都強于第二種。

Reference

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

繼續閱讀