zoukankan      html  css  js  c++  java
  • 字母异位词分组(Hash表映射)

    题目描述

    给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

    示例:

    输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
    输出:
    [
    ["ate","eat","tea"],
    ["nat","tan"],
    ["bat"]
    ]

    思路分析:

    构建一个哈希表,创建一个函数,只要字符串的字母相同,那么hash表映射的值就是一个定值,由此时间复杂度可达O(1).

     1 class Solution {
     2 public:
     3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
     4         vector<vector<string>> ans; //返回的参数
     5         unordered_map<int, int> mem; //hash表
     6         int size = 0;
     7         for(auto str: strs){
     8             int sum = 0;
     9             for(auto ch:str){
    10                 int index = hashgenerate(ch);
    11                 sum += index;
    12             }
    13             if(!mem.count(sum)){
    14                 vector<string> temp;
    15                 temp.push_back(str);
    16                 ans.push_back(temp);
    17                 mem[sum] = size++;
    18             }
    19             else{
    20                 int index = mem[sum];
    21                 ans[index].push_back(str);
    22             }
    23         }
    24         return ans;
    25     }
    26     //构建的Hash映射表
    27     int hashgenerate(char ch){
    28         int i = ch;
    29         return  ( 5 *i*i*i/26 + i*371 - i*i*997 + 99);
    30     }
    31 };
  • 相关阅读:
    Linux线程(一)
    模板(一)
    C++基础(八)
    C++基础(七)
    C++基础(六)
    C++基础(五)
    2.C#基础(二)
    1.C#基础(一)
    2.给出距离1900年1月1日的天数,求日期
    网络协议破解 SMTP
  • 原文地址:https://www.cnblogs.com/latencytime/p/14608883.html
Copyright © 2011-2022 走看看