1、题目描述
2、题目分析
首先将输入句子拆分成单词,在这个过程中将所有大写字母变换成小写字母,将每一个单词作为一个字符串放入一个 map<string,int> 容器中,最后遍历容器,查找出现次数最多且没有在banned中出现的字符串。
3、代码
1 string mostCommonWord(string paragraph, vector<string>& banned) { 2 3 4 map<string,int> m; 5 for( string::iterator it = paragraph.begin() ; it != paragraph.end(); ++it ){ 6 if( isalpha(*it) ){ 7 *it = std::tolower(*it) ; 8 auto it_i = it ; 9 while( it_i != paragraph.end() && isalpha( *it_i ) ){ 10 *it_i = std::tolower( *it_i ); 11 ++it_i; 12 } 13 string s( it,it_i ); 14 m[s]++; 15 it = (it_i == paragraph.end() )?it_i -1 : it_i ; 16 } 17 } 18 19 int count = 0; 20 string result; 21 for( auto it_m = m.begin(); it_m != m.end(); ++it_m ){ 22 if( find( banned.begin(), banned.end(),it_m->first ) == banned.end() && it_m->second > count ){ 23 result = it_m->first; 24 count = it_m->second; 25 } 26 } 27 28 return result ; 29 30 }