算法:找出相同字母组成的字符串Group Anagrams

说明

算法:找出相同字母组成的字符串Group Anagrams
地址: https://leetcode.com/problems/group-anagrams/

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

All inputs will be in lowercase.
The order of your output does not matter.

解决方法

实际为考察HashMap的用法,把字符串排序后当做key,把相同的相同字母组成的字符串放在list中为value。

private String sort(String input) {
    char[] chars = input.toCharArray();
    Arrays.sort(chars);
    return new String(chars);
  }

  public List<List<String>> groupAnagrams(String[] strs) {
    // edge check
    if (strs == null || strs.length == 0) {
      return null;
    }
    Map<String, List<String>> map = new HashMap<>();
    // build map
    for (String s: strs) {
      String sortItem = sort(s);
      if (!map.containsKey(sortItem)) {
        map.put(sortItem, new ArrayList<String>());
      }

      map.get(sortItem).add(s);
    }

    return new ArrayList<>(map.values());
  }

代码下载

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/hashtable/GroupAnagrams.java

发布了127 篇原创文章 · 获赞 12 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/zgpeace/article/details/103346574