LeetCode第 189 场周赛第二题简述:将一个句子中的单词按照单词字母数量的小大重新排列。
vector<string> svec
中的插入操作,push_back()
可以直接插入一个字符串,无需每个字母逐次push_back()
。
vector<string> svec;
string str;
svec.push_back(str);
map
和multimap
的本质就是map
的关键字key
只能对应唯一一个value
,multimap
的关键字可以对应多个value
,即multimap
允许多个相同的关键字key
存在。map
和multimap
在插入数据的时候有所不同:
void algoithm()
{
map<int, int> imap;
int arr[5] = { 1, 2, 3, 4, 5 };
int count = 0;
for (auto& i : arr)
imap[i] = count++; // multimap不允许关键字以数组的形式出现。
for (auto& i : imap)
cout << i.first << ":" << i.second << endl;
string ch[6] = { "I", "like", "Beijing", "university", "of", "technology" };
map<string, int> simap;
for (auto& str : ch)
simap[str] = count++; // multimap无法用此方法
for (auto& str : simap)
cout << str.first << ":" << str.second << endl;
}
运行截图:
所以可见,无论是map
还是multimap
,key
值无论是整型还是字符串型,均按照由小到大的顺序排列的。
- 下述例子讲述了
multimap
的错误示范:
multimap<string, int> simap;
simap["CSDN_blog"] = 1; // 错误语法,multimap无法使用该语法
map<string, int> simap;
simap["CSDN_blog"] = 1; // 正确语法
multimap
在插入数据的正确语法:
multimap<string, int> simap;
simap.insert(pair<string, int>("CSDN_blog", 1)); // 正确语法
将text
句子中的单词读取到vector
中的写法与答题时有不同,下面是最终题解。
string arrangeWords(string text){
text[0] += 32; // 首字母转变为小写
vector<string> svec;
multimap<int, string> ismap;
string::iterator iter = text.begin(), itertemp;
for (;; iter++) // 将单词存储到svec中
{
itertemp = iter;
iter = find(itertemp, text.end(), ' ');
string tempstr(itertemp, iter);
svec.push_back(tempstr);
if (iter == text.end())
break;
}
for (auto& word : svec) // 将单词存储到multimap中
ismap.insert(pair<int, string>((int)word.size(), word));
string textnew;
for (auto& word : ismap) // 将单词存储到string中
{
textnew += word.second;
textnew += " ";
}
textnew.pop_back(); // 最后一个空格去掉使用 pop_back()函数
textnew[0] -= 32; // 首字母大写
return textnew; // 返回排序号的句子
}