單詞識別:map 統計文中出現單詞個數

題目描述:

輸入一個英文句子,把句子中的單詞(不區分大小寫)按出現次數按從多到少把單詞和次數在屏幕上輸出來,要求能識別英文句號和逗號,即是說單詞由空格、句號和逗號隔開。
輸入描述:
輸入有若干行,總計不超過1000個字符。

輸出描述:

輸出格式參見樣例。

輸入

A blockhouse is a small castle that has four openings through which to shoot.

輸出

a:2
blockhouse:1
castle:1
four:1
has:1
is:1
openings:1
shoot:1
small:1
that:1
through:1
to:1
which:1

題目詳情:

https://www.nowcoder.com/practice/16f59b169d904f8898d70d81d4a140a0?tpId=94&tqId=31064&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fbit-kaoyan%2Fquestion-ranking&tPage=2

心得體會:

  1. 代碼一的設計思想是源自劉汝佳的算法書。要熟練利用 stringstream
  2. 注意 tolower 和 toupper 並不是要求參數必須是字母,非字母的字符也可以,只是這時會原樣輸出。比如 toupper 該函數等效返回大寫字母,如果存在這樣的值。否則保持不變
  3. map默認對鍵進行了排序,所以不需要調用sort。除非改變排序方式或者對值進行排序

代碼一:

#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<map>

using namespace std;
int main()
{
	string s,sum;
	map<string, int>n;
	while (cin >> s)
	{
		for (int i = 0; i < s.length(); i++)
		{
			if (isalpha(s[i]))
				s[i] = tolower(s[i]);
			else if (s[i] == ',' || s[i] == '.')
				s[i] = ' ';
		}
		stringstream ss(s);
		while (ss >> sum)
		{
			if (!n.count(sum))
				n[sum] = 0;
			n[sum]++;
		}
	}
	for (map<string, int>::iterator it = n.begin(); it != n.end(); it++)
		cout << (*it).first << ":" << (*it).second << endl;
	return 0;
}

心得體會:

  1. 代碼二是牛客網一個大佬寫的。比我的要簡潔的多
  2. #include <bits/stdc++.h> 是一個萬能的頭文件。大部分編譯器和OJ都支持。POJ 不支持,HDU 只有G++支持。其他基本都支持
  3. 單詞統計的話以後都可以用代碼二實現,很方便

代碼二:

//這道題的答案是按照字典序排列的,只要將map中的元素順序輸出即可。
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string s;
    while(getline(cin, s))
    {
        map<string, int> mp;
        string temp;
        for(int i = 0; i < s.size(); i++)
        {
            if(s[i] == ' ' || s[i] == ',' || s[i] == '.')   // 核心 
            {									// 遇到分隔符的話把一個單詞賦值到map
                if(temp != "")    
                    mp[temp]++;
                temp = "";
            }
            else                               //非分隔符的話把字符合成一個單詞(字符串)
            {
                temp += tolower(s[i]);        // 非字母字符的話不變直接賦值
            }
        }
        for(auto it = mp.begin(); it != mp.end(); it++)
        {
            cout << it->first << ":" << it->second << endl;
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章