• unordered_map算法


    unordered_maps

    遍历寻找符合键的元素: s.find(键)!=s.end()

    mapunordered_map都是C++ STL提供的关联容器,用于存储键-值对。它们之间的区别主要在于底层实现和搜索/插入/删除操作的性能表现:

    1. map是基于红黑树实现的,它会自动按照键的大小进行排序,因此键值对是有序存储的。在map中查找元素的时间复杂度为O(log n)
    2. unordered_map是基于哈希表实现的,它不保证元素插入的顺序,因为元素是根据哈希值存储的。在unordered_map中查找元素的时间复杂度为O(1),但可能会受到哈希冲突的影响。
    3. 可以直接对map的键值进行遍历操作

    409.最长回文串

    1. class Solution {
    2. public:
    3. int longestPalindrome(string s) {
    4. unordered_map<char,int>count;
    5. for(char ch:s)
    6. {
    7. count[ch]++;
    8. }
    9. int sum=0;
    10. bool sign=false;
    11. for(int i=0;isize();i++)
    12. {
    13. if(count[i]%2==0)
    14. {
    15. sum+=count[i];
    16. }
    17. else
    18. {
    19. sum+=count[i]-1;//减1就能构成回文
    20. sign=true;
    21. }
    22. }
    23. return sign?sum+1:sum;//存在奇数次字符多加1
    24. }
    25. };

     205.同构字符串

    1. class Solution {
    2. public:
    3. bool isIsomorphic(string s, string t) {
    4. unordered_map<char, char> s2, t2;
    5. for(int i=0;isize();i++)
    6. {
    7. char a=s[i],b=t[i];
    8. if((s2.find(a)!=s2.end()&&s2[a]!=b)||(t2.find(b)!=t2.end()&&t2[b]!=a)) //查找到键同时不符合已有映射关系
    9. {
    10. return false;
    11. }
    12. s2[a]=b;
    13. t2[b]=a;
    14. }
    15. return true;
    16. }
    17. };

     290.单词规律

    1. class Solution {
    2. public:
    3. bool wordPattern(string pattern, string s) {
    4. using namespace std;
    5. // 定义两个映射,一个用于字符到单词,一个用于单词到字符
    6. unordered_map<char, string> char_to_word;
    7. unordered_mapchar> word_to_char;
    8. vector words;
    9. istringstream ss(s); // 使用字符串流来分割字符串
    10. string word;
    11. // 将字符串 s 按照空格分割成单词
    12. while (ss >> word) {
    13. words.push_back(word);
    14. }
    15. // 检查单词的数量是否与模式字符的数量一致
    16. if (words.size() != pattern.size()) {
    17. return false;
    18. }
    19. for (int i = 0; i < pattern.size(); i++) {
    20. char c = pattern[i];
    21. string w = words[i];
    22. // 检查从模式字符到单词的映射是否已经存在且一致
    23. 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)))) {
    24. return false;
    25. }
    26. char_to_word[c] = w;
    27. word_to_char[w] = c;
    28. }
    29. return true;
    30. }
    31. }
    32. ;

     

  • 相关阅读:
    思腾云计算
    LPDDR4详解
    手把手教你用IDEA搭建SpringBoot并使用部署宝塔服务器
    Python自动化系统6
    利用pytorch 模型载入部分权重
    出行计划(2023寒假每日一题 16)
    DP4361国产六通道立体声D/A音频转换器芯片替代CS4361
    如何测试 Redis 缓存?
    SparkSQL联接操作
    python在线办公自动化oa系统django408
  • 原文地址:https://blog.csdn.net/2301_77869606/article/details/140051153