49. Ectopic letter word packet (java)

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
说明:

所有输入均为小写字母。
不考虑答案输出的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution one: super Violence Act

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        char[][] words = new char[strs.length][];
        ArrayList<List<String>> res = new ArrayList<>();
        for(int i = 0; i < strs.length; i++) {
            words[i] = strs[i].toCharArray();
            Arrays.sort(words[i]);
        }
        boolean[] visited = new boolean[strs.length];
        for(int i = 0; i < strs.length; i++){
            if(visited[i]) continue;
            ArrayList<String> tmp = new ArrayList<>();
            tmp.add(strs[i]);
            visited[i] = true;
            for(int j = i+1; j < strs.length; j++){
                if(Arrays.equals(words[i], words[j])){
                    tmp.add(strs[j]);
                    visited[j] = true;
                } 
            }
            res.add(tmp);
        }
        return res;
    }
}

Solution two: Hash

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
        Map<String, List> map = new HashMap<String, List>();
        for(int i = 0; i < strs.length; i++) {
            char[] ch = strs[i].toCharArray();
            Arrays.sort(ch);
            String key = String.valueOf(ch);
            if(!map.containsKey(key)) map.put(key,new ArrayList());
            map.get(key).add(strs[i]); 
        }
        return new ArrayList(map.values());
    }
}
Published 141 original articles · won praise 19 · views 8163

Guess you like

Origin blog.csdn.net/weixin_43306331/article/details/104089114