leetcode48.字母异位词分组

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

示例:

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

输出: [

  • ["ate","eat","tea"],

  • ["nat","tan"],

  • ["bat"] ]

说明:

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

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

分析:由于都是小写字母,所以数组中只有26种字符,即a-z。可以用hash表的方式进行统计。首先对数组中的数据进行处理,统计数组中每个字符串中的字符出现的次数,用#分割。例如“bat“#1#1#0....,“abe”#1#1#0#0#1...,再使用hash表进行统计。

package leetcode;

import java.util.*;

/**
 * @author Livingdd
 * 2019/7/29 22:44
 **/
public class leet49 {
    public List<List<String>> groupAnagrams(String[] strs) {

        Map<String,List<String>> result = new HashMap<>();
        int[] array = new int[26];
        for(String temp : strs){
            Arrays.fill(array,0);
            for(int i = 0;i < temp.length();i++){
                char c = temp.charAt(i);
                array[c - 'a']++;
            }
            StringBuilder sb = new StringBuilder();
            for(int i = 0;i<26;i++){
                sb.append('#');
                sb.append(array[i]);
            }
            if(result.containsKey(sb.toString())) result.get(sb.toString()).add(temp);

            else {
                List<String> list  = new ArrayList<String>();
                list.add(temp);
                result.put(sb.toString(),list);
            }
        }
        Collection<List<String>> collection =  result.values();
        return new ArrayList<>(collection);
    }

    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        leet49 l = new leet49();
        System.out.println(l.groupAnagrams(strs));
    }
}

复制代码

转载于:https://juejin.im/post/5d4eb6b6f265da03a9502698

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值