1. 程式人生 > 其它 >Leetcode: NO.49 字母異位詞分組

Leetcode: NO.49 字母異位詞分組

技術標籤:演算法

題目

給定一個字串陣列,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字串。

示例:

輸入: ["eat", "tea", "tan", "ate", "nat", "bat"]
輸出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
說明:

所有輸入均為小寫字母。
不考慮答案輸出的順序。

連結:https://leetcode-cn.com/problems/group-anagrams

解題記錄

  • 將字元中的字元重新排序作為key,然後用map將同樣key的放到一個list,然後將這些list轉存到list中返回即可
/**
 * @author: ffzs
 * @Date: 2020/12/14 上午10:25
 */


public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>
> map = new HashMap<>(); for (String s : strs) { char[] c = s.toCharArray(); Arrays.sort(c); String str = new String(c); if (!map.containsKey(str)) map.put(str, new ArrayList<>()); map.get(str).add(s); } return
new ArrayList<>(map.values()); } }

image-20201214105125195