LeetCode-4.6-美区-49-M-字母异位词分组(Move Zeroes)

文章目录


给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
iven an array of strings, group anagrams together.

示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。

思路

(1)LeetCode-Sort-242-E:有效的字母异位词(Valid Anagram)

解法1

class Solution{
	public List<List<String>> groupAnagrams(String[] strs) {
       HashMap<String,Integer> map=new HashMap();
       List<List<String>> res=new ArrayList();
       int k=0;
       for(int i=0;i<strs.length;i++){
           char[] tmp=strs[i].toCharArray();
           Arrays.sort(tmp);
           String tmp1=new String(tmp);
         
           if(map.get(tmp1)!=null){
               int n=map.get(tmp1.toString());
               List<String> l=res.get(n);
               l.add(strs[i]);
               res.set(n,l);
           }
           else{
               map.put(tmp1,new Integer(k));
               k=k+1;
               List<String> templ=new ArrayList();
               templ.add(strs[i]);
               res.add(templ);
               
           }
       }
        return res;
    }
}

解法2

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        int i;
        List<List<String>> ans = new ArrayList<List<String>>();
        String[] tstr = new String[strs.length];
        //boolean[] checked = new boolean[strs.length];
        HashMap<String,ArrayList<String>> map = new HashMap<String,ArrayList<String>>();
        //System.out.println(tstr[0]);
        for(i = 0;i<strs.length;i++) {
            char[] tar = new char[strs[i].length()];
            tar = strs[i].toCharArray();
            Arrays.sort(tar);
            String key = new String(tar);
           if(map.containsKey(key)) {
               ArrayList<String> tl = map.get(key);
               tl.add(strs[i]);
               map.put(key,tl);
           } else {
               ArrayList<String> tl = new ArrayList<String>();
               tl.add(strs[i]);
               map.put(key,tl);
           }
        }
        
       return  new ArrayList<List<String>>(map.values());
    }
}
发布了194 篇原创文章 · 获赞 20 · 访问量 7950

猜你喜欢

转载自blog.csdn.net/Xjheroin/article/details/105351098