当前位置:网站首页>49. Grouping of alphabetic ectopic words: give you a string array, please combine the alphabetic ectopic words together. You can return a list of results in any order. An alphabetic ectopic word is a

49. Grouping of alphabetic ectopic words: give you a string array, please combine the alphabetic ectopic words together. You can return a list of results in any order. An alphabetic ectopic word is a

2022-07-05 13:21:00 ? abc!

Title Description

Here's an array of strings , Would you please Letter heterotopic word Put together . You can return a list of results in any order .

Letter heterotopic word Is a new word obtained by rearranging the letters of the source word , Letters in all source words are usually used just once .

Example 1:
Input : strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
Output : [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
Example 2:
Input : strs = [“”]
Output : [[“”]]
Example 3:
Input : strs = [“a”]
Output : [[“a”]]

Ideas

From the meaning of the topic :

  1. The two strings are mutually alphabetic ectopic words , need The two strings contain the same letters
  2. So right. The two strings are sorted separately The resulting string must be the same
  3. Use a hash table to store each set of alphabetic ectopic words , The key of the hash table is the symbol of a group of letter ectopic words , The value of the hash table is a list of alphabetic ectopic words
  4. Take the sorted string as the key of the hash table

Code

class Solution {
    
    public List<List<String>> groupAnagrams(String[] strs) {
    
        // The hash table : The sorted string is used as the key of the hash table , The value is a list of alphabetic ectopic words 
        Map<String,List<String>> map = new HashMap<String,List<String>>();
        // Create loop , Traverse each string 
        for(String str : strs){
    
            // Split the string into an array of characters 
            char[] array = str.toCharArray();
            // Sort the array 
            Arrays.sort(array);
            // Convert the sorted character array to a string as map Key 
            String key = new String(array);
            //map.getOrDefault(key,defaultValue): When Map There's this in the collection key when , Just use this key Corresponding value value , If you don't have this key Just use the default values defaultValue
            List<String> list = map.getOrDefault(key,new ArrayList<String>());
            // Save the current string to list Collection 
            list.add(str);
            // Deposit it in map in 
            map.put(key,list);
        }
        return new ArrayList<List<String>>(map.values());
    }
}

Code instructions

Note see ...

原网站

版权声明
本文为[? abc!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051318550140.html