酷代码 AI
菜单
服务商

编程实现:统计文章中特定单词出现次数与首次位置,附代码详解

```cpp #include <iostream> #include <string> #include <cctype> // 转换为小写字母 void toLowerCase(std::string &str) { for (char &c : str) { c = std::tolower(c); } } int main() { std::string target; std::string article; // 读取目标单词 std::cin >> target; // 读取文章 std::cin.ignore(); std::getline(std::cin, article); // 将目标单词和文章都转换为小写 toLowerCase(target); toLowerCase(article); int count = 0; int firstPos = -1; int pos = 0; while (pos < article.length()) { // 跳过前导空格 while (pos < article.length() && article[pos] == ' ') { pos++; } int wordStart = pos; std::string currentWord; // 提取当前单词 while (pos < article.length() && article[pos] != ' ') { currentWord += article[pos]; pos++; } // 检查当前单词是否与目标单词匹配 if (currentWord == target) { count++; if (firstPos == -1) { firstPos = wordStart; } } } if (count > 0) { std::cout << count << " " << firstPos << std::endl; } else { std::cout << -1 << std::endl; } return 0; } ``` 代码解释: 1. `toLowerCase` 函数:将字符串中的所有字母转换为小写,以便在不区分大小写的情况下进行匹配。 2. 主函数 `main`: - 读取目标单词和文章。 - 将目标单词和文章都转换为小写。 - 初始化计数器 `count` 和首次出现位置 `firstPos` 为 -1。 - 遍历文章,跳过前导空格,提取当前单词。 - 检查当前单词是否与目标单词匹配,如果匹配则增加计数器,并记录首次出现位置。 3. 输出结果:如果找到目标单词,则输出出现次数和首次出现位置;否则输出 -1。 复杂度分析: - 时间复杂度:$O(n)$,其中 $n$ 是文章的长度。 - 空间复杂度:$O(m)$,其中 $m$ 是目标单词的长度。 ######[AI问答 | 590点数解答 | 2025-12-15 16:21:39]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]