每日算法题:19.7.29

本文介绍了一种用于将字母异位词进行分组的算法实现,通过示例展示了如何将具有相同字母但排列不同的字符串归类到一起,如['eat', 'tea', 'ate']被视为一组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

示例:

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

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

代码:

public class Test18 {
    @Test
    public void test(){
        String[] test =new String[]{"",""};
        List<List<String>> lists = new Test18().groupAnagrams(test);
        for (List<String> list : lists) {
            System.out.println("list = " + list);
        }

    }
    public List<List<String>> groupAnagrams(String[] strs) {
        List<String> strings = Arrays.asList(strs);
        List<List<String>> result = new ArrayList<>();
        function(result,new ArrayList<>(strings));
        return result;
    }

    public void function(List<List<String>> result,List<String> strings){
        if (strings.size()==0) {
            return;
        }

        if (strings.size()==1) {
            result.add(strings);
            return;
        }

        List<String> temp = new ArrayList<>();
        temp.add(strings.get(0));
        char[] chars = strings.get(0).toCharArray();
        strings.remove(0);
        if (chars.length==0) {
            for (int i = 0; i < strings.size(); i++) {
                if (strings.get(i)=="") {
                    temp.add(strings.remove(i));
                }
            }
        }else{
            List<Character> temp1 = new ArrayList<>();
            for (char aChar : chars) {
                temp1.add(aChar);
            }
            for (int i = 0; i < strings.size(); i++) {
                List<Character> temp2 = new ArrayList<>();
                for (char aChar : strings.get(i).toCharArray()) {
                    temp2.add(aChar);
                }
                if (temp1.containsAll(temp2) && !temp.contains(strings.get(i))) {
                    temp.add(strings.get(i));
                    strings.remove(i);
                }
            }
        }
        result.add(temp);
        function(result,strings);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值