LC49. 字母异位词分组

先来看一下我一开始的愚蠢的做法

/**
 * @Classname Solution1
 * @Description TODO
 * @Date 2020/1/12 22:47
 * @Author SonnSei
 */
public class Solution1 {

    public static List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ret = new ArrayList<>();
        for(String str:strs){
            boolean find = false;
            for(int i = 0;i<ret.size();i++){
                if(check(str,ret.get(i).get(0))){
                    ret.get(i).add(str);
                    find = true;
                    break;
                }
            }
            if(!find){
                List<String> newList = new ArrayList<>();
                newList.add(str);
                ret.add(newList);
            }
        }
        return ret;
    }

    private static boolean check(String s1,String s2){
        if(s1.length() != s2.length())return false;
        char[] c1=s1.toCharArray();
        char[] c2 = s2.toCharArray();
        Arrays.sort(c2);
        Arrays.sort(c1);
        for(int i = 0 ; i < c1.length;i++){
            if(c1[i]!=c2[i])return false;
        }
        return true;
    }
}

优化后

/**
 * @Classname Solution2
 * @Description TODO
 * @Date 2020/1/12 23:09
 * @Author SonnSei
 */
public class Solution2 {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
        List<List<String>> ret = new ArrayList<>();
        Map<String, List> map = new HashMap<>();
        for (String str : strs) {
            char[] chars=str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            if (map.containsKey(key)) {
                map.get(key).add(str);
            } else {
                ArrayList<String> list =new ArrayList();
                list.add(str);
                map.put(key,list );
                ret.add(list);
            }
        }
        return ret;
    }
}
发布了140 篇原创文章 · 获赞 2 · 访问量 1890

猜你喜欢

转载自blog.csdn.net/weixin_40602200/article/details/103951154
今日推荐