Leetcode刷题. 哈希表数据结构的应用
哈希表数据结构:
unordered_map<string, int> myMap = {{"apple", 3}, {"banana", 5}, {"orange", 2}};
// 使用基于范围的 for 循环遍历 unordered_map
for (const auto& pair : myMap) {
cout << pair.first << ": " << pair.second << endl; // 输出键和值
}
// 使用迭代器遍历 unordered_map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << it->first << ": " << it->second << endl; // 输出键和值
}
这里题型通常为简单题型,但是考察对基础知识的掌握,以及灵活应用。
这道题目主要是考察对于奇数回文串的处理,例如对于 "ccc"这种情况,在判断是奇数的时候,需要单独加上对应的个数。
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> umap;
for (char ch : s) {
umap[ch] += 1;
}
int single = 0;
for (auto &pair : umap) {
if (pair.second % 2 == 0) {
res += pair.second;
} else {
res += pair.second - 1;
single = 1;
}
}
return res + single;
}
};
原文地址:https://blog.csdn.net/GouDanAndOcean/article/details/143030669
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!