leetcode-49 Group Anagrams

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

题意就是根据相同字符组成的字符串进行一个归类:

方法一:对数组进行遍历 找出相同组的数据  并使得该位置的数据为null  遍历不同组的数据

    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        for (int i = 0; i < strs.length; i++) {
            List<String> tmp = new ArrayList<>();
            String tmpValue = strs[i];
            if (tmpValue!=null) {
                tmp.add(tmpValue);
                for (int j = i + 1; j < strs.length; j++) {
                    if (strs[j] !=null && isGroup(tmpValue, strs[j])) {
                        tmp.add(strs[j]);
                        strs[j] = null;
                    }
                }
                res.add(tmp);
            }

        }
        return res;
    }
    
    public boolean isGroup(String a,String b) {
        if(a== null || b== null) {
            return false;
        }
        
        if(a.equals(b)) {
            return true;
        }
        if(a.length() == b.length()) {
            char [] as=  a.toCharArray();
            char [] bs = b.toCharArray();
            Arrays.sort(as);
            Arrays.sort(bs);
            for(int index=0;index<a.length();index++) {
                if(as[index] != bs[index]) {
                    return false;
                }
            }
            return true;
        }
        
        return false;
        
    }

方法二: 调用map  对每个数据进行获取一个key  该key为排序后的值

    public List<List<String>> groupAnagramsBetter(String[] strs) {
        if (strs.length == 0) return new ArrayList<>();
        Map<String, List<String>> ans = new HashMap<>();
        for (String s : strs) {
            char[] ca = s.toCharArray();
            Arrays.sort(ca);
            String key = String.valueOf(ca);
            if (!ans.containsKey(key)) ans.put(key, new ArrayList<>());
            ans.get(key).add(s);
        }
        return new ArrayList<>(ans.values());
        
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值