微信网站改版价格,东莞网站建设 乐云践新,北京网站建设公司服务哪家好,做ps找图的网站unordered_mapchar, chars
遍历寻找符合键的元素: s.find(键)!s.end()
map和unordered_map都是C STL提供的关联容器#xff0c;用于存储键-值对。它们之间的区别主要在于底层实现和搜索/插入/删除操作的性能表现#xff1a;
map是基于红黑树实现的#xff0c;它会…unordered_mapchar, chars
遍历寻找符合键的元素: s.find(键)!s.end()
map和unordered_map都是C STL提供的关联容器用于存储键-值对。它们之间的区别主要在于底层实现和搜索/插入/删除操作的性能表现
map是基于红黑树实现的它会自动按照键的大小进行排序因此键值对是有序存储的。在map中查找元素的时间复杂度为O(log n)。unordered_map是基于哈希表实现的它不保证元素插入的顺序因为元素是根据哈希值存储的。在unordered_map中查找元素的时间复杂度为O(1)但可能会受到哈希冲突的影响。可以直接对map的键值进行遍历操作
409.最长回文串
class Solution {
public:int longestPalindrome(string s) {unordered_mapchar,intcount;for(char ch:s){count[ch];}int sum0;bool signfalse;for(int i0;icount.size();i){if(count[i]%20){sumcount[i];}else{sumcount[i]-1;//减1就能构成回文signtrue;}}return sign?sum1:sum;//存在奇数次字符多加1}
}; 205.同构字符串
class Solution {
public:bool isIsomorphic(string s, string t) {unordered_mapchar, char s2, t2;for(int i0;is.size();i){char as[i],bt[i];if((s2.find(a)!s2.end()s2[a]!b)||(t2.find(b)!t2.end()t2[b]!a)) //查找到键同时不符合已有映射关系{return false;}s2[a]b;t2[b]a;}return true;}
}; 290.单词规律
class Solution {
public:bool wordPattern(string pattern, string s) {using namespace std;// 定义两个映射一个用于字符到单词一个用于单词到字符unordered_mapchar, string char_to_word;unordered_mapstring, char word_to_char;vectorstring words;istringstream ss(s); // 使用字符串流来分割字符串string word;// 将字符串 s 按照空格分割成单词while (ss word) {words.push_back(word);}// 检查单词的数量是否与模式字符的数量一致if (words.size() ! pattern.size()) {return false;}for (int i 0; i pattern.size(); i) {char c pattern[i];string w words[i];// 检查从模式字符到单词的映射是否已经存在且一致if ((char_to_word.find(c) ! char_to_word.end()(char_to_word[c] ! w))||((word_to_char.find(w) ! word_to_char.end()(word_to_char[w] ! c)))) {return false;} char_to_word[c] w;word_to_char[w] c;}return true;}}
;