关于这道题的双指针思想可以看一下这道语法题 熟悉一下
小知识:
- 哈希表!!!关于哈希表的遍历:
- 用迭代器遍历
unordered_map<string,int>::iterator item;
for (item = hash.begin(); item != hash.end(); item ++ )
if (item->second > cnt || (item->second == cnt && item->first < res))
{
res = item->first;
cnt = item->second;
}
- 用auto范围遍历
for (auto item : hash)
{
if (item.second > cnt || (item.second == cnt && item.first < res))
{
res = item.first;
cnt = item.second;
}
}
- 关于这个
check(c)
是用来检测字符是不是数字字母,这里有一个函数可以直接用
#include <cctype>的函数
函数名称 | 返回值 |
---|---|
isalnum() | 如果参数是字母数字,即字母或数字,该函数返回true |
tolower() / toupper() | 如果参数是(小)大写字符,则返回其(大)小写,否则返回该参数 |
isalpha() / isdigit() | 如果参数是字母或数字(0~9),该函数返回真 |
islower() / isupper() | 如果参数是,该函数返回true |
小步骤:
getline(cin, str)
读入一整行- 提取每个单词,双指针的思想!
- 把单词扣出来之后存入哈希表
unordered_map<string, int> hash;
- 然后遍历哈希表,找次数最多的单词
//语法题好像又一道类似的
#include<iostream>
#include<unordered_map>
using namespace std;
bool check(char c)
{
if (c >= 'A' && c <= 'Z') return true;
if (c >= 'a' && c <= 'z') return true;
if (c >= '0' && c <= '9') return true;
return false;
}
int main()
{
string str;
getline(cin, str);
unordered_map<string, int> hash;
// 提取每个单词,这里用了双指针
for (int i = 0; i < str.size(); i ++ )
{
if (check(str[i])) // 如果这一位合法,那他一定是开头!
{
int j = i;
string word;
while(j < str.size() && check(str[j])) word += tolower(str[j ++ ]) ;
hash[word] ++ ;
i = j;
}
}
// 存答案
string res;
int cnt = -1;
for (auto item : hash)
{
if (item.second > cnt || (item.second == cnt && item.first < res))
{
res = item.first;
cnt = item.second;
}
}
cout << res << ' ' << cnt << endl;
return 0;
}
新手学的比较吃力,如果有问题欢迎您指出!!
你好,整个流程我看懂了,还有一些问题,想请教你一下,就是:
在遍历的时候if里面的第二个条件没看明白,我在想如果同=用迭代器遍历的时候,我每次把单词出现的次数存下来,然后找到最大的次数,我不知道怎么通过次数找到对应的单词,可以帮忙看一下吗?
if的第二个条件是:
如果常用词有多个,则输出字典序最小的那个单词。
(题中要求哦)我觉得有可能会有两个单词出现次数相同的情况呢
哈希表是
key-value
的形式,你想要反着找,就同时开两个unordered_map 一个是[HTML_REMOVED]另一个是[HTML_REMOVED]就可以了<string, int> 和 <int, string>
实在不好意思,我这边没有提示,重新做题的时候才发现您回复我了,万分感谢,是我没仔细读题,谢谢大佬
hh我是新手,我们一起学习吧!
wow 谢谢大佬!