找出n个字符串中出现次数最多的字符串(创新工场)

来源:互联网 发布:淘宝淘气值650是多少钱 编辑:程序博客网 时间:2024/06/02 09:08

C/C++:

char* find(char **data,int n);

说明:

1. data是字符串数组,n是数组中字符串的个数,返回值为出现次数最多的字符串。

2. 若结果有多个,返回任意一个即可

3. 不得使用任何库函数/API,如需使用类似功能, 请自行实现

4. 算法效率尽可能高,尽量少的使用内存空间

5. 必须要有代码注释和算法说明

例如:data里面的数据是{“paper”,”cup”,”book”,”cup”,”pen”,”book”}。n = 6。返回结果为”cup”或”book”。

#include<iostream>#include<string>#include<assert.h>#include<map>using namespace std;char *strcpy(char *p,const string temp){    int i=0,k=0;    while(temp[i])        p[k++]=temp[i++];    p[k]='\0';    return p;}char* find(char **data,int n){    assert(*data!=NULL||n>0);    map<string,int>mvc;    int i,Max=0x80000000;    string temp;    char*p=new char[100];    for(i=0;i<n;i++)        mvc[data[i]]++;    map<string,int>::iterator it;    for(it=mvc.begin();it!=mvc.end();it++)    {        if(it->second>Max)        {            Max=it->second;            temp=it->first;        }    }    return strcpy(p,temp);   //return const_cast<char *>(temp.c_str());}int main(){    char *name[6]={"paper","cup","book","cup","pen","book"};    string temp=find(name,6);    cout<<temp<<endl;}


0 0