LeetCode [Hash Table]: Anagrams

Source: Internet
Author: User

LeetCode [Hash Table]: Anagrams

Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.

Idea: Sort all the letters of each word in alphabetical order, and sort the results as keys. All words with the same key are combined into an anw.group. Finally, all anetag groups are returned.

class Solution {public:    vector
 
   anagrams(vector
  
    &strs) {        vector
   
     result;        unordered_map
    
     > dict;        for (auto word : strs)            dict[getLetters(word)].push_back(word);        for (auto wordGroup : dict)            if (wordGroup.second.size() > 1)                result.insert(result.end(), wordGroup.second.begin(), wordGroup.second.end());        return result;    }private:    string getLetters(string word) {        string letters;        for    (auto letter : word) {            int i;            for (i = 0; i < letters.size(); ++i)                if (letters[i] > letter)                    break;            letters.insert(letters.begin() + i, letter);        }        return letters;    }};
    
   
  
 


In the above solution, the insertion sorting algorithm written by myself is used for sorting each word in alphabetical order, or the sort function can be used.

class Solution {public:    vector
 
   anagrams(vector
  
    &strs) {        vector
   
     result;        unordered_map
    
     > dict;        for (auto word : strs){            string tmp = word;            sort(tmp.begin(), tmp.end());            dict[tmp].push_back(word);        }        for (auto group : dict)            if (group.second.size() > 1)                result.insert(result.end(), group.second.begin(), group.second.end());        return result;    }};
    
   
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.