1. 程式人生 > >2017百度面試現場coding演算法一

2017百度面試現場coding演算法一

求字串中字元的出現次數,並按照字典序排列
輸入:“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; }