This is the 9th day of my participation in the August Wen Challenge.More challenges in August

Grouping of letter ectopic words

Description: Given an array of strings, combine alphabetic anemic words together. An anagram is a string with the same letters but different arrangements.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/gr… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: Hash the weight

A Hashmap (tempResult) is declared to record the temporary result, where key is the alphabetic anemic word, that is, the alphabetic string of the same sort. Value is a collection of strings arranged differently with the same letter heteroposition, traversing STRS:

  • First, the current STR is converted to the character array chars, and then theArrays.sort(chars)The chars array is converted to the string sortedStr, which is the same string as the alphabetic ectopic word, and then determines whether sortedStr exists in the key of the tempResult. If not, initialize a List to values. Add the current STR to the list, and then place the corresponding key (sortedStr) and the corresponding values into the tempResult; If sortedStr exists in the key of the tempResult, the current STR is added to the list corresponding to sortedStr. Then process the next string.

Finally, values of tempResult are returned as the final result.

import java.util.*;

public class LeetCode_049 {
    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> tempResult = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String sortedStr = String.valueOf(chars);
            if (tempResult.get(sortedStr) == null) {
                List<String> values = new ArrayList<>();
                values.add(str);
                tempResult.put(sortedStr, values);
            } else {
                tempResult.get(sortedStr).add(str);
            }
        }
        List<List<String>> result = new ArrayList<>();
        result.addAll(tempResult.values());
        return result;
    }

    public static void main(String[] args) {
        String[] strs = new String[]{"eat"."tea"."tan"."ate"."nat"."bat"};
        List<List<String>> lists = groupAnagrams(strs);
        for (List<String> list : lists) {
            for (String s : list) {
                System.out.print(s + ""); } System.out.println(); }}}Copy the code

【 Daily message 】 Life is always unexpected warmth and endless hope, no matter what time to see the front, full of hope will be invincible.