题解:P12278 [蓝桥杯 2024 国 Python A] 设置密码

· · 题解

~很毒瘤的判断~

思路

先输入 T,接着循环 T 次,每次输入一行字符串,遍历字符串,记录大写字母、小写字母、数字、特殊字符的数量。特别的,特殊字符串说的是种类,不是个数,所以要用 set 或 map。最后照着题意判断。时间复杂度是 O(Tn\log n),可以通过本题数据。

AC code

#include<bits/stdc++.h>
using namespace std;
int t;
string s;
int main(){
    cin>>t;
    cin.ignore();//清空换行
    while(t--){
        getline(cin,s);//一次读入一行,防止有空格(提交了好几次才发现)
        int big=0,sma=0,num=0;//记录
        set<char> els;//题目是说“种类”,不是个数(提交了好几次才发现)
        if(s.length()<6){//不符合条件直接跳出
            cout<<"0\n";
            continue;
        }
        int f=0;
        for(char c: s){
            if('A'<=c&&c<='Z') big++;
            else if('a'<=c&&c<='z') sma++;
            else if('0'<=c&&c<='9') num++;
            else if(c=='~'||c=='!'||c=='@'||c=='#'||c=='$'||c=='%'||c=='^'||c=='&'||c=='*'||c=='('||c==')'||c=='_')
                els.insert(c);
            else{
                f=1;//不符合条件直接跳出
                break;
            }
        }
        if(f){
            cout<<"0\n";
            continue;
        }
        //计算种类
        int z=0;
        if(big) z++;if(sma) z++;if(num) z++;if(!els.empty()) z++;
        //判断
        if((z==4||(z==3&&els.size()>=3))&&s.length()>=12){//z==4的时候,特殊字符不一定是>=3
            cout<<"3\n";
            continue;
        }
        if(z>=2&&s.length()>=8){
            cout<<"2\n";
            continue;
        }
        cout<<"1\n";
    }
    return 0;
}
import sys

def main():
    t = int(sys.stdin.readline())
    for _ in range(t):
        s = sys.stdin.readline().strip()

        # 长度检查
        if len(s) < 6:
            print(0)
            continue

        # 初始化标志
        has_upper = False
        has_lower = False
        has_digit = False
        specials = set()
        valid = True

        # 检查每个字符
        for c in s:
            if 'A' <= c <= 'Z':
                has_upper = True
            elif 'a' <= c <= 'z':
                has_lower = True
            elif '0' <= c <= '9':
                has_digit = True
            elif c in {'~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_'}:
                specials.add(c)
            else:
                valid = False
                break

        # 非法字符检查
        if not valid:
            print(0)
            continue

        has_special = len(specials) > 0
        type_count = sum([has_upper, has_lower, has_digit, has_special])
        special_count = len(specials)

        # 密码强度判断
        if len(s) >= 12:
            # 强密码条件1: 包含全部四种类型
            strong1 = has_upper and has_lower and has_digit and has_special
            # 强密码条件2: 包含三种类型(含特殊字符)且特殊字符种类≥3
            strong2 = type_count >= 3 and has_special and special_count >= 3

            if strong1 or strong2:
                print(3)
                continue

        if len(s) >= 8 and type_count >= 2:
            print(2)
            continue

        print(1)

if __name__ == "__main__":
    main()

本人为 c 党,python 代码是 deepseek 帮我改写的,如有错误,请谅解。
~代码来之不易,给个赞呗。~