判斷密碼是否「安全」,需同時滿足:
8 ~ 16 字符之間(含)。A-Za-z0-9~ ! @ # $ % ^對每類字符編寫正則,用 Pattern.compile(regex).matcher(str).find() 判斷是否存在。統計滿足類別數,≥3 輸出 YES,否則 NO。
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");
}
}
}
#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;
}
~!@#$%^,正則中需轉義 ^(在字符類中首位不轉義也可,寫作 [~!@#$%^])。Scanner.nextLine() 讀整行,注意 nextInt() 後需消耗換行符。O(L) 每個密碼,L ≤ 50 極快。