1、题目描述

LeetCode 题解之Most Common Word-LMLPHP

2、题目分析

首先将输入句子拆分成单词,在这个过程中将所有大写字母变换成小写字母,将每一个单词作为一个字符串放入一个 map<string,int> 容器中,最后遍历容器,查找出现次数最多且没有在banned中出现的字符串。

3、代码

 string mostCommonWord(string paragraph, vector<string>& banned) {

         map<string,int> m;
for( string::iterator it = paragraph.begin() ; it != paragraph.end(); ++it ){
if( isalpha(*it) ){
*it = std::tolower(*it) ;
auto it_i = it ;
while( it_i != paragraph.end() && isalpha( *it_i ) ){
*it_i = std::tolower( *it_i );
++it_i;
}
string s( it,it_i );
m[s]++;
it = (it_i == paragraph.end() )?it_i - : it_i ;
}
} int count = ;
string result;
for( auto it_m = m.begin(); it_m != m.end(); ++it_m ){
if( find( banned.begin(), banned.end(),it_m->first ) == banned.end() && it_m->second > count ){
result = it_m->first;
count = it_m->second;
}
} return result ; }
05-11 19:24