社区讨论

这是我通过的代码

P1308[NOIP 2011 普及组] 统计单词数参与者 4已保存回复 3

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
3 条
当前快照
1 份
快照标识符
@mj436fu8
此快照首次捕获于
2025/12/13 17:21
3 个月前
此快照最后确认于
2025/12/13 17:25
3 个月前
查看原帖

代码

要考虑句首有没有空格
CPP
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;

int main()
{
    // 考虑连续空格和句首空格
    int idx = 0, q_idx = -1, q_flg = 0;
    string query, sentence, word;
    map<string, int> m;
    getline(cin, query);
    transform(query.begin(), query.end(), query.begin(), ::tolower);
    getline(cin, sentence);
    transform(sentence.begin(), sentence.end(), sentence.begin(), ::tolower);
    if (sentence.find(query+" ") != string::npos) // 句首,且有其他单词
    {
        if (sentence[sentence.find(query+" ")-1]== ' '||
            sentence[sentence.find(query+" ")]==0)
        {
            q_idx = sentence.find(query+ " ");
        }
    }
    if (sentence.find(" "+query+" ") != string::npos) // 句中,且有其他单词
    {
        if (q_idx==-1)
        {
            q_idx = sentence.find(" "+query+" ")+1;
        }
    }
    if (sentence.find(" "+query) != string::npos) // 句尾
    {
        if (q_idx==-1)
        {
            q_idx = sentence.find(" "+query)+1;
        }

    }
    if (sentence.compare(query)==0) //句子为1个单词
    {
        if (q_idx==-1)
        {
            q_idx=0;
        }

    }
    stringstream ss(sentence);
    while (ss >> word)
    {
        if (m.find(word) == m.end())
        {
            m.insert(pair<string, int>(word, 1));
        }
        else
        {
            m[word]++;
        }
    }
    if (m.find(query) != m.end())
    {
        cout << m[query] << " " << q_idx;
    }
    else
    {
        cout << -1;
    }
    return 0;
}

回复

3 条回复,欢迎继续交流。

正在加载回复...