LeetCode 49. Group Anagrams HashTable

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]Note:
  • All inputs will be in lowercase.
  • The order of your output does not matter.

解法:

  首先遍历输入,同时对每个string按 字典序 排序;(为了使相同字母异构 经hashtable映射得到相同的值)

  排序后相同的value 进入同一个字符数组

     核心在于排序

class Solution {
public:

    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string,vector<string>> m;
        vector<vector<string>> res;
        for(int i = 0; i < strs.size(); i++){
            string s = strs[i];
            sort(s.begin(),s.end());// 先对每个字符串排序
            m[s].push_back(strs[i]); // 相同字母异构的字符串 经排序后  原来的异构字符串被 映射到一个同一个位置,
            //并用string存储原来的值
        }

        for(auto ss : m){
            vector<string> level = ss.second;
            res.push_back(level);
        }
        return res;
    }
};

原文地址:https://www.cnblogs.com/dingxi/p/11571300.html

时间: 2024-10-16 07:06:06

LeetCode 49. Group Anagrams HashTable的相关文章

Leetcode 49. Group Anagrams

Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat",

19.2.7 [LeetCode 49] Group Anagrams

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","

[leetcode]49. Group Anagrams变位词归类

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","

[leetcode]49. Group Anagrams重排列字符串分组

是之前的重排列字符串的延伸,判断是重排列后存到HashMap中进行分组 这种HashMap进行分组的方式很常用 public List<List<String>> groupAnagrams(String[] strs) { /* 其实重排列的那个题是有两种做法的,之前整理的是比较好的的一种字母哈希表的方法,还有一种方法 是把字符串排序,然后进行比较就行. 这个题正好就是用了排序的方法,排序后的字符串作为key,list作为value就行 一开始想用字母哈希表的方法,结果没做出来

LeetCode开心刷题二十六天——49.Group Anagrams

49. Group Anagrams Medium 1824116FavoriteShare Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat

49. Group Anagrams(js)

49. Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], [&q

【一天一道LeetCode】#49. Group Anagrams

一天一道LeetCode系列 (一)题目 Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"

【LeetCode】49. Group Anagrams

Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat",

【Leetcode】Group Anagrams

题目链接:https://leetcode.com/problems/anagrams/ 题目: Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", &q