[LeetCode] [Java] Anagrams

Source: Internet
Author: User

[LeetCode] [Java] Anagrams
Question:

 

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

Note: All inputs will be in lower-case.

Question:

Given a string array, all multipart word combinations are returned.

Note: All input values are in lower case.

 

Algorithm analysis:

In fact, the inverted word structure is quite understandable, that is, the two words contain the same characters and numbers, but the order is different.

 

Sort the letters in a string, and the strings that are re-arranged are equal.

Based on the above ideas, a map is used to record the strings sorted by letters and their location (or original string). During traversal, if the sorted strings are equal, it means that the two are in the same order.

The first occurrence of the reordered string requires special care. In the following code, use-1 to identify whether the first occurrence of the reordered string has been added to the result.

In addition, you can sort strings alphabetically by the char array of the Java class library. You can also sort the string containing only lowercase letters.


AC code:

 

Public ArrayList
 
  
Anagrams (String [] strs) {ArrayList
  
   
List = new ArrayList
   
    
(); HashMap
    
     
Map = new HashMap
     
      
(); For (int I = 0; I <strs. length; ++ I) {char [] chars = strs [I]. toCharArray (); Arrays. sort (chars); String anort = new String (chars); if (map. containsKey (aney) {int index = map. get (ansible); if (index! =-1) {list. add (strs [index]); map. put (anager,-1); // use-1 to identify the first re-arranged string} list. add (strs [I]);} else map. put (ansible, I);} return list ;}
     
    
   
  
 


 

 

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.