一次 read() 读完整份输入,sum(生成器) 逐字符统计非空格、非换行的字符,一遍扫描即达到 Ω(|s|) 输入下界的最优。
OJ: roj
题目 ID: 3654
难度:入门
标签:python字符串输入输出
创建: 2026-10-02 13:31
更新: 2026-10-06 16:00
题目描述
给定字符串 Ca 45 → 4。
思路
遍历每个字符,非空格且非换行则计数,输出计数器。
参考代码
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 13:31
# update_at: 2026-10-02 13:31
import sys
SKIP = ' \n\r' # 题面规定不计入统计的字符:空格与换行(\r 兼容 CRLF 行尾)
def solve() -> None:
"""统计标题字符串中不为空格、不为换行的字符个数。"""
title = sys.stdin.buffer.read().decode() # 一次读完整份输入,行内空格原样保留
print(sum(ch not in SKIP for ch in title))
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-06 16:00
* update_at: 2026-10-06 16:00
*/
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
getline(cin, s); // 读入整行(包含空格)
int cnt = 0;
for (size_t i = 0; i < s.size(); i++) {
char ch = s[i];
if (ch != ' ' && ch != '\n' && ch != '\r')
cnt++;
}
// 注意:题目说输入只有一行,getline 读整行即可;
// 若标题跨行,应改用循环读完整份输入再统一过滤。
cout << cnt << '\n';
return 0;
}