LeetCode 49 Group_Anagrams Java实现
来源:互联网 发布:类似ostagram的软件 编辑:程序博客网 时间:2024/05/16 13:00
题目在注释里,直接看有点乱,先说说大体思路:
就是将每个字符串遍历一遍再存到set中,如果装结果的map中有一样的set,则认为已经遇到过一样的字母的字符串,然后通以set作为key从map中拿到装索引值的list,将索引值添加进去。遍历完了再通过
List< HashSet< Character>> group拿到对应的索引再返回。
该解法不适合字符串中有重复字母的情况。。。时间复杂度算不出来>﹏<不过应该挺好。
import java.util.ArrayList;import java.util.HashMap;import java.util.HashSet;import java.util.List;/** * no.49 * 给出一个字符串数组,将其索引可以通过颠倒顺序产生相同结果的单词进行分组 * 如["eat","tea","ate"],["nat","tan"],返回字符串数组组成的数组。 * 输入:["eat","nat","tea","tan","bat","ate"] * @author 煎鱼 * map * * HashMap<HashSet<Character>, Integer> map = new HashMap<>(); HashSet<Character> set1 = new HashSet<>(); HashSet<Character> set2 = new HashSet<>(); set1.add('a'); set2.add('a'); set1.add('b'); set2.add('b'); map.put(set1, 1); System.out.println(map.containsKey(set2)); 返回true,证明set可以作为key */public class Group_Anagrams { public static List<List<String>> solution(String[] arr){ List<HashSet<Character>> group = new ArrayList<>();//装组合 HashMap<HashSet<Character>, List<Integer>> map = new HashMap<>();//所有数据 for(int i = 0; i<arr.length; i++) { HashSet<Character> character = new HashSet<>();//记录 for(int j = 0; j < arr[i].length(); j++) { character.add(arr[i].charAt(j)); } if(map.containsKey(character)) { List<Integer> index = map.get(character);//装set的索引 index.add(i); map.put(character, index); }else { List<Integer> index = new ArrayList<Integer>();//装set的索引 index.add(i); group.add(character); map.put(character, index); } } //返回 List<List<String>> res = new ArrayList<>();//结果 for(int i = 0; i < group.size(); i++) { List<Integer> index = map.get(group.get(i));//结果索引 List<String> g = new ArrayList<>();//装字符串 for(int j = 0; j < index.size(); j++) { g.add(arr[index.get(j)]); } res.add(g); } return res; } public static void main(String[] args) { String[] arr = new String[] {"eat","nat","tea","tan","bat","ate"}; System.out.println(solution(arr).toString()); }}
返回: [[eat, tea, ate], [nat, tan], [bat]]
阅读全文
0 0
- LeetCode 49 Group_Anagrams Java实现
- leetcode题--Java实现
- LeetCode java实现ZigZagConversion
- leetcode Sort Colors java实现
- 【Leetcode】Sort List JAVA实现
- LeetCode LRU Cache (Java实现)
- [leetcode]18.4Sum(Java实现)
- Leetcode题目汇总-Java实现
- 【Leetcode】java实现KMP算法
- LeetCode:Reorder List C++与Java实现
- leetcode Length of Last Word java实现
- leetcode Swap Nodes in Pairs java实现
- 【Leetcode】Maximum Product Subarray JAVA实现
- 169Majority Element [LeetCode Java实现]
- LeetCode中的Valid Palindrome用Java实现
- LeetCode中的Isomorphic Strings 的java实现
- LeetCode中Count Primes的java实现
- * LeetCode【2】. Add Two Numbers--java实现
- 【BZOJ2744】【二分图】[HEOI2012]朋友圈 题解
- 十月小结,过去的一个月内,我收获了什么?
- 一致性哈希算法(consistent hashing)
- 初学Qt:QCheckBox
- Linux下使用unzip命令解压war包
- LeetCode 49 Group_Anagrams Java实现
- SSH与SSM学习之Spring20——Spring事务之Spring相关的基础
- CSS格式
- Codeforces 834A
- Error:Execution failed for task ':app:processDebugManifest'
- 美联航事件的系统思考
- Hadoop集群安装
- java作业
- 在c语言中宏和函数的区别