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 };
  • 相关阅读:
    pandas Dataframe filter
    process xlsx with pandas
    data manipulate in excel with easyExcel class
    modify registry in user environment
    add number line in vim
    java import webservice
    ctypes MessageBoxA
    music 163 lyrics
    【python实例】自动贩卖机
    【python基础】sys模块(库)方法汇总
  • 原文地址:https://www.cnblogs.com/latencytime/p/14608883.html
Copyright © 2011-2022 走看看