牛牛的密码

GitHub跳转原题关系图返回列表

一次扫描把字符按 ASCII 区间分入四个桶,append 顺序天然保序,等级为非空桶数。

OJ: roj

题目 ID: 10000

难度:入门

标签:入门字符串模拟python

创建: 2026-10-02 17:17

更新: 2026-10-04 21:36

题目描述

给定非空字符串 ss。把字符按四类拆出并保留原相对顺序:小写 a-z、大写 A-Z、数字 0-9、其余特殊字符。输出 password level:X(XX 为非空部分数),再按上述顺序输出四部分,空串输出 (Null)。

思路

一次扫描字符串,按 ASCII 区间把每个字符 push 进对应桶,桶内顺序即原串相对顺序。扫描结束后统计非空桶数得到等级,再逐桶输出,空桶替换为 (Null)。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-10-02 17:20
# update_at: 2026-10-02 17:20

import sys

EMPTY = "(Null)"  # 某一部分为空时的占位输出


def solve() -> None:
    # 题面保证密码不含空格等空白字符,第一个 token 就是整个字符串
    data = iter(sys.stdin.buffer.read().split())
    s = next(data).decode()

    # 四部分按题面顺序分桶;逐字符 append,桶内自然保持原串的相对顺序
    lower: list[str] = []
    upper: list[str] = []
    digit: list[str] = []
    other: list[str] = []
    for ch in s:
        if "a" <= ch <= "z":
            lower.append(ch)     # 第一部分:小写英文字母
        elif "A" <= ch <= "Z":
            upper.append(ch)     # 第二部分:大写英文字母
        elif "0" <= ch <= "9":
            digit.append(ch)     # 第三部分:数字
        else:
            other.append(ch)     # 第四部分:其余特殊字符

    parts = (lower, upper, digit, other)
    level = sum(map(bool, parts))  # 每个非空部分让密码等级 +1
    out = [f"password level:{level}"]
    out += ["".join(part) if part else EMPTY for part in parts]
    print("\n".join(out))


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-04 21:36
 * update_at: 2026-10-04 21:36
 */
#include <iostream>
#include <string>
using namespace std;

typedef long long ll;

string s;              // 输入的密码串
string bucket[5];      // bucket[1..4] 分别对应小写、大写、数字、其他四类字符

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> s;

    // 一次扫描,把字符按 ASCII 区间分到四个桶,append 顺序天然保序
    for (size_t i = 0; i < s.size(); i++) {
        char c = s[i];
        if ('a' <= c && c <= 'z') {
            bucket[1].push_back(c);
        } else if ('A' <= c && c <= 'Z') {
            bucket[2].push_back(c);
        } else if ('0' <= c && c <= '9') {
            bucket[3].push_back(c);
        } else {
            bucket[4].push_back(c);
        }
    }

    int level = 0;
    for (int i = 1; i <= 4; i++) {
        if (!bucket[i].empty()) {
            level++;
        }
    }

    cout << "password level:" << level << "\n";
    for (int i = 1; i <= 4; i++) {
        if (bucket[i].empty()) {
            cout << "(Null)\n";
        } else {
            cout << bucket[i] << "\n";
        }
    }

    return 0;
}