【LeetCode】 118 字母異位詞分組

題目:

image-20210207023528595

這題牛客網的題目我感覺出的有問題,如果有兩三組呢,怎麼能是ArrayList<String>返回值

image-20210207023438578

image-20210207023448348

解題思路:

由於互爲字母異位詞的兩個字符串包含的字母相同,因此對兩個字符串分別進行排序之後得到的字符串一定是相同的,故可以將排序之後的字符串作爲哈希表的鍵。

https://leetcode-cn.com/problems/group-anagrams/solution/zi-mu-yi-wei-ci-fen-zu-by-leetcode-solut-gyoc/

代碼:

import java.util.*;

public class LC101 {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String str : strs) {
            char[] array = str.toCharArray();
            Arrays.sort(array);
            String key = new String(array);
            List<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<List<String>>(map.values());
    }

    public static void main(String[] args) {
        LC101 lc = new LC101();
        String[] arr = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> res = lc.groupAnagrams(arr);
        for (int i = 0; i < res.size(); i++) {
            System.out.println(res.get(i));
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章