Skip to content

[LeetCode] 49. 字母异位词分组 #65

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Sep 4, 2019 · 0 comments
Open

[LeetCode] 49. 字母异位词分组 #65

Animenzzzz opened this issue Sep 4, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

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

示例:

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

说明:
所有输入均为小写字母。
不考虑答案输出的顺序。

解题思路:使用哈希表。首先一次遍历,将每个单词按照字母排序,然后将排好序的单词作为key,没排序的单词(原单词)为值存进字典。同时用set容器存好排完序的单词(为了便于第二次从map中取出来)。第二次遍历,遍历set容器,将map中的值取出

C++解题:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        set<string> sorStrs_set;
        unordered_map<string,vector<string>> map;
        for (int i = 0; i < strs.size(); i++)
        {
            string tmp = strs[i];
            sort(tmp.begin(),tmp.end());
            map[tmp].push_back(strs[i]);
            sorStrs_set.insert(tmp);
        }

        for(set<string>::iterator it=sorStrs_set.begin() ;it!=sorStrs_set.end();it++)
        {
            vector<string> tmp = map[*it];
            res.push_back(tmp);
        }
        return res;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant