题解 洛谷 Luogu P1308 [NOIP2011 普及组] 统计单词数 C++

题目传送门:

P1308 [NOIP2011 普及组] 统计单词数 - 洛谷 | 计算机科学教育新生态https://www.luogu.com.cn/problem/P1308getline() 会清除使当次 getline() 终止的换行,而 cin 不会

因此 cin 以换行终止,之后还需要 getline() 的话,需要用 getchar() 吞换行

Linux 的一些相关环境中,tolower 还有一个宏版本,洛谷 C++ 环境就是这样的

在此情况下,要将 tolower 当作函数调用时,需要用 "::" 指明

每次用 find() 找,找得到且判定为单词,cnt 就 ++

单词判定及后续处理细节在代码注释里

代码:

cpp 复制代码
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
    string s, t;
    cin >> s;
    getchar();
    getline(cin, t);
    transform(s.begin(), s.end(), s.begin(), ::tolower);
    transform(t.begin(), t.end(), t.begin(), ::tolower);
    int pos = 1E9, cnt = 0, p, a = 0;
    while ((p = t.find(s)) != -1)
    {
        if (s.size() == t.size() /* t == s */ \
            || (p == 0 && t[p + s.size()] == ' ') /* p 在 t 起始位置,且 p + s.size() 子串后是单词分割符 */ \
            || (p > 0 && t[p - 1] == ' ' && p + s.size() == t.size()) /* p + size()子串前是单词分隔符,后是 t 末尾 */ \
            || (p > 0 && t[p - 1] == ' ' && t[p + s.size()] == ' ')) /* p + size() 子串前后都是单词分隔符 */
            cnt++, pos = (p + a < pos ? p + a : pos);
        a += p + s.size();//pos 代表在原始 t 中第一个出现的位置,但 t 进行了很多次 erase 操作,需要统计前面删掉的长度,这样的 t.find(s) + a 才能赋值给 pos
        t.erase(0, p + s.size());//
        while(t[0] != ' ') t.erase(0, 1), a++;//每次需要删掉整个单词,而不一定是 (0, p + s.size())。如对于 s = i,t = iii,第二次删除后 t = i,这是不对的,应该一次就把 t 删完
    }
    if (!cnt) cout << -1;
    else cout << cnt << ' ' << pos;
    return 0;
}
相关推荐
点云SLAM31 分钟前
C++中的算术转换、其他隐式类型转换和显示转换详解
c++·static_cast·dynamic_cast·c++中的类型转换·算术类型转换·其他隐式类型转换·显示类型转换
Zfox_1 小时前
Git 进阶之路:高效协作之分支管理
大数据·linux·运维·c++·git·elasticsearch
wenchm1 小时前
细说STM32单片机FreeRTOS任务管理API函数vTaskList()的使用方法
c语言·c++·stm32·单片机·嵌入式硬件
wuqingshun3141591 小时前
蓝桥杯 10.拉马车
数据结构·c++·算法·职场和发展·蓝桥杯·深度优先
不是仙人的闲人2 小时前
算法之动态规划
数据结构·c++·算法·动态规划
rigidwill6662 小时前
LeetCode hot 100—分割等和子集
数据结构·c++·算法·leetcode
眠りたいです3 小时前
Linux-网络基础
linux·运维·服务器·网络·c++·进程间通信
姝孟3 小时前
学习笔记(C++篇)--- Day 3
c++·笔记·学习
天堂的恶魔9463 小时前
C++项目 —— 基于多设计模式下的同步&异步日志系统(3)(日志器类)
c++·算法·设计模式
whoarethenext4 小时前
使用c++调用deepseek的api(附带源码)
服务器·开发语言·c++·qt·deepseek