题解
[NOIP 2011 普及组] 统计单词数
1 条题解
-
0
1. 解题思路
**核心方法:**先将单词和文章统一为小写,再按空格切分文章,逐个比较完整单词。
2. 坑点和注意事项
- 匹配必须是完整单词,保留原文章空格以计算首次位置;下标从0开始。文章长度≤10^6,int可保存位置。
/* 思路:先将单词和文章统一为小写,再按空格切分文章,逐个比较完整单词。 关键规则与坑点:匹配必须是完整单词,保留原文章空格以计算首次位置;下标从0开始。文章长度≤10^6,int可保存位置。 时间复杂度:O(L+W),L为文章长度,W为目标长度。空间复杂度:O(L+W)。 */ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string word, text; getline(cin, word); getline(cin, text); for (int i = 0; i < (int)word.size(); i++) { word[i] = tolower((unsigned char)word[i]); } for (int i = 0; i < (int)text.size(); i++) { text[i] = tolower((unsigned char)text[i]); } int count = 0, first = -1; for (int i = 0; i < (int)text.size();) { if (text[i] == ' ') { i++; continue; } int j = i; while (j < (int)text.size() && text[j] != ' ') { j++; } // 先将单词和文章统一为小写,再按空格切分文章,逐个比较完整单词。 if (text.substr(i, j - i) == word) { count++; if (first < 0) { first = i; } } i = j; } if (count) { cout << count << ' ' << first << "\n"; } else { cout << -1 << "\n"; } }3. 复杂度
- **时间复杂度:**O(L+W),L为文章长度,W为目标长度。
- **空间复杂度:**O(L+W)。
- 1