首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

HDU 2043 密碼:正則表達式驗證密碼強度的 Java 實現

     編輯:C++ 入門

題目要求

判斷密碼是否「安全」,需同時滿足:

  1. 長度在 8 ~ 16 字符之間(含)。
  2. 包含以下四類字符中的至少三類:
  • 大寫字母 A-Z
  • 小寫字母 a-z
  • 數字 0-9
  • 特殊符號 ~ ! @ # $ % ^

解法:正則表達式逐類檢查

對每類字符編寫正則,用 Pattern.compile(regex).matcher(str).find() 判斷是否存在。統計滿足類別數,≥3 輸出 YES,否則 NO。

Java 完整代碼

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

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        sc.nextLine(); // 吞掉換行
        while (m-- > 0) {
            String pwd = sc.nextLine();
            if (pwd.length() < 8 || pwd.length() > 16) {
                System.out.println("NO");
                continue;
            }
            int cnt = 0;
            if (Pattern.compile("[A-Z]").matcher(pwd).find()) cnt++;
            if (Pattern.compile("[a-z]").matcher(pwd).find()) cnt++;
            if (Pattern.compile("[0-9]").matcher(pwd).find()) cnt++;
            if (Pattern.compile("[~!@#$%^]").matcher(pwd).find()) cnt++;
            System.out.println(cnt >= 3 ? "YES" : "NO");
        }
    }
}

C++ 版本 (無正則庫,手動檢查)

#include <bits/stdc++.h>
using namespace std;

int main() {
    int m; cin >> m;
    string s;
    while (m--) {
        cin >> s;
        if (s.size() < 8 || s.size() > 16) { cout << "NO\n"; continue; }
        bool has[4] = {};
        for (char c : s) {
            if (c >= 'A' && c <= 'Z') has[0] = true;
            else if (c >= 'a' && c <= 'z') has[1] = true;
            else if (c >= '0' && c <= '9') has[2] = true;
            else has[3] = true; // 特殊符號
        }
        int cnt = has[0] + has[1] + has[2] + has[3];
        cout << (cnt >= 3 ? "YES" : "NO") << '\n';
    }
    return 0;
}

關鍵點總結

  1. 長度檢查優先,不合格直接跳過後續判斷。
  2. 特殊符號集合固定:~!@#$%^,正則中需轉義 ^(在字符類中首位不轉義也可,寫作 [~!@#$%^])。
  3. Java Scanner.nextLine() 讀整行,注意 nextInt() 後需消耗換行符。
  4. 時間複雜度 O(L) 每個密碼,L ≤ 50 極快。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved