单词统计问题

来源:互联网 发布:淘宝淡季是几月份 编辑:程序博客网 时间:2024/06/05 09:44

华为OJ
输入一行英文文本,要求输出出现频率最高和最低的单词,中间以,.和空格进行分割,大小不同的单词视为同一个,如果单词数目相同,则输出第一次出现的那个。输出均为小写形式。如”Hello world, i said hello world to the world.”输出world,i
代码如下:

#include <iostream>#include<vector>#include<string>#include<algorithm>using namespace std;bool cmp(pair<string,int> data,pair<string,int> data2){    return (data.second > data2.second);}int main(){       string patter =", .";    string source ="Hello world, i said        hello world to the world....";    transform(source.begin(),source.end(),source.begin(),tolower);    vector<string> result;    int size = source.size();    int i = 0;    for(;i < size;i++)    {        auto found = source.find_first_of(patter,i);        if(found != string::npos)        {            result.push_back(source.substr(i,found-i));            i = found;        }        else            break;    }    if(i != size-1)    {        result.push_back(source.substr(i));    }    for(auto it = result.begin();it != result.end();)    {        if(*it == "" || *it =="." || *it ==",")            it = result.erase(it);        else            ++it;    }    vector<pair<string,int>> r;    for(int i = 0;i < result.size();++i)    {        r.push_back(make_pair(result[i],1));        for(int j = 0;j < r.size()-1;++j)        {            if(result[i] == r[j].first)            {                r[j].second++;                r.pop_back();                break;            }           }    }    stable_sort(r.begin(),r.end(),cmp);    cout<<r[0].first<<",";    for(int i = 0;i < r.size();++i)    {        if(r[i].second == 1)        {            cout<<r[i].first<<endl;            break;        }    }}
0 0
原创粉丝点击