#include<iostream>
#include<algorithm>
#include<map>
#include<string>
#include<vector>
#include<functional>
using namespace std;
void SortWord(char *str)
{
if (str == NULL)
return;
map <string, int> m;
//将char*分割成string 类型的单词存到map中并统计数量
char *p = str;//两个指针从字符串中分割单词
while (*str)
{
if (*str == ' '||*str == '\0')
{
m[string (p, str)]++;
p = str + 1;
}
str++;
}
//实际是按照string排序的map,但是我们需要按照出现的次数排序
cout << "=========map中的按照string排序的原始数据" << endl;
for (auto i : m) {
cout << i.first << " " <<i.second<< endl;
}
//方式一:按照map中的value进行排序,插入到multimap中即可
multimap<int, string ,greater<int>>m2;
for (auto i : m)
{
m2.insert(make_pair(i.second, i.first));
}
cout << "=========multimap<int,string>按照出现次数排序的数据" << endl;
for (auto i : m2) {
cout << i.second << " " << i.first << endl;
}
//方式二,对map中的数据插入到vector中,然后对vector排序
vector<pair<string, int>> v;
for (auto i : m)
{
v.push_back(i);
}
sort(v.begin(), v.end(), [](pair<string, int>p1, pair<string, int>p2) {return p1.second > p2.second; });
cout << "=============vector<pair<string,int>> 按照出现次数sort" << endl;
for (auto i : v)
{
cout << i.first << " " << i.second << endl;
}
cin.get();
}
struct _word{
int count;
char word[32];
}Word[100];
int i = 0;
bool cmp(_word w1, _word w2)
{
return w1.count > w2.count;
}
void bubblesort()
{
for (int j = 0; j < i; ++j)
{
for (int k = 0; k < i - 1- j; ++k)
{
// if (strcmp(Word[k].word, Word[k + 1].word) < 0)
if(Word[k].count < Word[k+1].count)
{
// _word temp = { 0 };
// memcpy(&temp, &Word[k], sizeof(_word));
// memcpy(&Word[k],&Word[k+1], sizeof(_word));
// memcpy(&Word[k+1],&temp, sizeof(_word));
swap(Word[k], Word[k + 1]);
}
//相同次数按照字典序排序
else if (Word[k].count == Word[k + 1].count)
{
if (strcmp(Word[k].word, Word[k + 1].word) > 0)
{
swap(Word[k], Word[k + 1]);
}
}
}
}
}
void CWordSort(const char *str) {
if (str == NULL)return;
const char *p = str;
while (*str)//收集单词存到数组中
{
if (*str == '\0' || *str == ' ')
{
int len = str - p;
int j = 0;
for (; j < i; j++)
{
if (strncmp(Word[j].word, p,len) == 0)
{
Word[j].count++;
break;
}
}
if (j == i)
{
strncpy_s(Word[i].word, p, len);
Word[i++].count++;
}
p = str + 1;
}
str++;
}
cout << "C语言方式收集到的单词=====" << endl;
for (int j = 0; j < i; j++)
{
cout << Word[j].word << " " << Word[j].count << endl;
}
cout << "==============C bubble sort==============" << endl;
bubblesort();//自己写的冒泡排序函数
//sort(Word, Word + i, cmp);//调用库函数的sort函数
for (int j = 0; j < i; j++)
{
cout << Word[j].word << " " << Word[j].count << endl;
}
cin.get();
}
int main()
{
const char * str = "hello hi world hello cpp hello world const ";
SortWord(const_cast<char*>(str));
CWordSort(str);
return 0;
}
腾讯面试题----对字符串中单词出现次数排序总结
最新推荐文章于 2024-05-06 14:44:53 发布