編寫一種方法,對字符串數組進行排序,將所有變位詞組合在一起。變位詞是指字母相同,但排列不同的字符串。
注意:本題相對原題稍作修改
示例:
輸入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
輸出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
說明:
- 所有輸入均為小寫字母。
- 不考慮答案輸出的順序。
解題思路
因為變位詞是指字母相同,但排列不同的字符串。因此我們可以對字符串進行排序,將字符串按字典序排列,而變位詞的字母是相同的,因此排序以后的結果對于所有變位詞應該是相同的。
代碼
class Solution {public List<List<String>> groupAnagrams(String[] strs) {Map<String,List<String>> map=new HashMap<>();for (String str : strs) {char[] c=str.toCharArray();Arrays.sort(c);String s = new String(c);if(!map.containsKey(s)){map.put(s,new ArrayList<>());}map.get(s).add(str);}List<List<String>> res=new ArrayList<>();for (Map.Entry<String, List<String>> entry : map.entrySet()) {res.add(entry.getValue());}return res;}
}