P1308 统计单词数

本文详细解析了洛谷平台上的P1308题目,通过C++代码展示了如何读取输入字符串,比较目标字符串并统计其出现次数及首次出现的位置。适用于初学者理解和实践字符串操作和基本算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.luogu.com.cn/problem/P1308

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

static vector<string> g_inputList;
static vector<int> g_inputListIndex;

void getInput()
{
    char ctmp;
    int numOfInput = 0;
    char strInput[11] = {0};
    int index = 0;

    while (1)
    {
        int isEof = scanf("%c", &ctmp);
        if (isEof == EOF || '\n' == ctmp || ' ' == ctmp)
        {
            if (numOfInput > 0)
            {
                g_inputList.push_back(strInput);
                g_inputListIndex.push_back(index-numOfInput);
                memset(strInput, 0, sizeof(strInput));
                numOfInput = 0;
            }

            if (isEof == EOF || '\n' == ctmp)
            {
                break;
            }
        }
        else
        {
            if (ctmp >= 'A' && ctmp <= 'Z')
            {
                strInput[numOfInput] = ctmp + 0x20;
            } 
            else
            {
                strInput[numOfInput] = ctmp;
            }
            numOfInput++;
        }
        index++;
    }
}

int main()
{
    string word;
    getInput();
    word = g_inputList[0];
    g_inputList.clear();
    g_inputListIndex.clear();

    getInput();
    int n = g_inputList.size();
    int outputNum = 0;
    int outputIndex = 0;
    for (int i = 0; i < n; i++)
    {
        if (word == g_inputList[i])
        {
            if (0 == outputNum)
            {
                outputIndex = g_inputListIndex[i];
            }
            outputNum++;
        }
    }
    if (outputNum)
    {
        cout << outputNum << ' ' << outputIndex << endl;
    } 
    else
    {
        cout << "-1" << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值