LC49——字母异位词分组

41 阅读1分钟

49. 字母异位词分组

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

  示例 1:

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

示例 2:

输入: strs = [""]
输出: [[""]]

示例 3:

输入: strs = ["a"]
输出: [["a"]]

 

提示:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] 仅包含小写字母

** 解答:**

  • 将每个词排个序,作为key,如果已经存在,就分为一组,不存在,独立一个分组
import java.util.*;

public class LetterAllotroleClass {
    public static List<List<String>> groupAnagrams(String[] strs) {
        if (strs == null) return null;
        HashMap<String, List<String>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            char[] arrays = strs[i].toCharArray();
            Arrays.sort(arrays);
            System.out.println("sort : "+Arrays.toString(arrays));
            if (map.containsKey(Arrays.toString(arrays))) {
                List<String> mlist = map.get(Arrays.toString(arrays));
                mlist.add(strs[i]);
                map.put(Arrays.toString(arrays), mlist);
            } else {
                List<String> mlist = new ArrayList<>();
                mlist.add(strs[i]);
                map.put(Arrays.toString(arrays), mlist);
            }
        }

        List<List<String>> result = new ArrayList<>();
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            result.add(map.get((String) iterator.next()));
        }
        return result;
    }

   //test
    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> result = groupAnagrams(strs);
        for (int i = 0; i < result.size(); i++) {
            List<String> mid = result.get(i);
            for (int j = 0; j < mid.size(); j++) {
                System.out.print(mid.get(j) + ", ");
            }
            System.out.println("-----");
        }
    }
}