您的位置:首页 > 职场人生

2017百度面试现场coding算法一

2017-04-23 17:20 344 查看
求字符串中字符的出现次数,并按照字典序排列

输入:“I am a student a boy”

输出:[(I,1),(a,2),(am,1),(boy,1),(student,1)]

(注意字符串截取的规则,注意最后单词的处理,注意比较函数的引用)

struct Item{
string word;
int count;
};
bool compare(Item &a,Item &b)
{
return a.word<b.word;
}
vector<Item> wordNum(string weight)
{
vector<Item> vec;
int len=weight.length();
int s=0;
for(int i=0;i<=len;i++)
{
if(weight[i]==' '||weight[i]=='\0')
{   string str=weight.substr(s,i-s);
s=i+1;
Item temp;
int flag=0;
for(int j=0;j<vec.size();j++)
{
if(vec[j].word==str)
{   vec[j].count++;
flag=1;
break;
}
}
if(flag==0)
{
temp.count=1;
temp.word=str;
vec.push_back(temp);
}
}
}
sort(vec.begin(),vec.end(),compare);
return vec;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  百度 面试 算法 函数