扫描文章中的独立单词,忽略大小写与给定单词比较,统计出现次数并记录首次真实下标。
OJ: roj
题目 ID: 1400
难度:入门
标签:字符串模拟python
创建: 2026-09-30 08:35
更新: 2026-10-05 12:53
题目描述
给定一个只含字母的单词 -1。
思路
文章中的独立单词由空格分隔,连续多个空格也要正确跳过;遍历文章提取每个单词,统一转小写后与目标单词比较,相等则计数并记录首次出现位置。
参考代码
Python 版:
python
# ROJ 1400 统计单词数:按空格切分文章,独立单词忽略大小写与给定单词完全相同才算匹配
import sys, re
def main() -> None:
lines = sys.stdin.read().splitlines() # 按行整体读入,保留文章中的空格与真实下标
w = lines[0].lower() # 给定单词,统一转小写实现忽略大小写
hits = [m.start() for m in re.finditer(r'\S+', lines[1]) if m.group().lower() == w] # 命中单词首字母下标
print(f"{len(hits)} {hits[0]}" if hits else -1)
if __name__ == '__main__':
main()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-05 12:53
* update_at: 2026-10-05 12:53
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string w; // 给定单词,统一转小写
string s; // 文章
// 将字符串统一转小写
void to_lower(string &t) {
for (ll i = 0; i < (ll)t.size(); i++) {
if (t[i] >= 'A' && t[i] <= 'Z') t[i] = t[i] - 'A' + 'a';
}
}
int main() {
getline(cin, w);
getline(cin, s);
to_lower(w);
ll cnt = 0; // 出现次数
ll first = -1; // 首次出现位置
ll n = s.size();
ll i = 0;
while (i < n) {
// 跳过连续空格
while (i < n && s[i] == ' ') i++;
if (i >= n) break;
// 记录当前单词起点,并截取完整单词
ll start = i;
string cur;
while (i < n && s[i] != ' ') {
cur.push_back(s[i]);
i++;
}
to_lower(cur);
if (cur == w) {
cnt++;
if (first == -1) first = start;
}
}
if (cnt == 0) {
cout << -1 << "\n";
} else {
cout << cnt << " " << first << "\n";
}
return 0;
}