Leetcode --- anagrams ()

Source: Internet
Author: User

Notice:

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

For example:

Input:["Tea", "and", "ate", "eat", "den"]

Output:["Tea", "ate", "eat"]

Interface:Vector<String>Anagrams(Vector<String>&STRs);

 

Solution:

Words with different sequences composed of the same letters must be the same after sorting, so they can be stored in the map, and finally the values greater than 1 can be retrieved from the map, that is, the letter "people" composed of the same letters"

For example, ["ate", "tea", "AET", "eat", "HgT", "gf", "ATG ", "gat"] for this container, we first sort the ATE dictionary, convert it to AET, and then put it into map. The map structure here is

Map <string, vector <string>

After 7 words are traversed, the map structure is as follows:

Key value [0] value [1] value [2] value [3]

AET ate tea AET eat

Ght HgT

FG GF

Agt atg gat

After traversing the map, put the words "who" with the number of values greater than 1 into the res array,

The anagrams In the res Array

Two groups of anagrams will be output here

 1   Class  Solution {  2  Public  :  3 Vector < String > Anagrams (vector < String > & STRs ){  4 Map < String , Vector < String > M;  5 Vector < String > Res;  6      For ( Int I = 0 ; I <STRs. Size (); I ++ ){  7         String S = STRs [I];  8 Sort (S. Begin (), S. End ()); //  Sort  9 M [s]. push_back (STRs [I]); //  Insert Map  10  }  11   12       For (Map < String , Vector < String >>:: Iterator I = M. Begin (); I! = M. End (); I ++ ){  13         If (I-> second). Size ()> 1  )  14           For ( Int It =0 ; It <(I-> second). Size (); It ++ )  15 Res. push_back (I-> second) [it]); //  Output  16   }  17       Return  Res;  18   }  19 };

PS: You must have a deep understanding of the map usage in STL. The key-value can be of various types, including the container type. Size () and other built-in functions are also common.

 

 

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.