Group Anagrams--java的实现方式

来源:互联网 发布:清华网络学堂 编辑:程序博客网 时间:2024/06/05 05:24

          为了准备两个月后的校招,最近一直忙着刷算法题,LeetCode上的算法题很经典,可惜量还是蛮大的,我采用的是按类型进行刷题,正好也可以集中学习和总结每一块知识点,今天看到这道题,第一想法是用HashMap来做,下面我做了两种结果,我会给大家展示出来。


        问题





        解析

        1.首先先遍历字符串数组里面的每个元素,将它取出并转换成字符类型。
       2.转换成字符类型,便可以用Arrays.sort对每一个字符进行排序,再将排序完的字符转换成字符串。
       3.创建一个HashMap,这里面key和value采用什么类型很关键,将决定后面实现的难易程度。
       4.接下来用新创建的HashMap中的containsKey来判断,最后就是将HashMap中value添加到list结合中并返回。
 

       我做的两个版本主要区别在于如何将HashMap中value添加到list结合中

       1.第一种是用Map.Entry遍历HashMap的方式。
       2.第二种是ArrayList的构造方法来将HashMap中value添加到collection中。



        第一种解决方案

         1.第一种是用Map.Entry遍历HashMap的方式。

public class Solution {    public List<List<String>> groupAnagrams(String[] strs) {        List<List<String>>li =new ArrayList<>();Map<String,List<String>>map=new HashMap<>();String num="";for(int i=0;i<strs.length;i++){ char[]ch=strs[i].toCharArray(); Arrays.sort(ch); num=String.valueOf(ch); if(map.containsKey(num)){ map.get(num).add(strs[i]);  }else{ List<String>list=new ArrayList<>(); list.add(strs[i]); map.put(num,list); }      }        //第一种解决方案通过Map.Entry         Set<Map.Entry<String, List<String>>>set2=map.entrySet();      Iterator<Map.Entry<String, List<String>>>iterator2=set2.iterator();       while (iterator2.hasNext()) {    Map.Entry<String, List<String>> map3=iterator2.next();     List<String> st= new ArrayList<>();     st=map3.getValue();     li.add(st);}        return li;     }      } 


           2.通过LeetCode提交后的详情




         第二种解决方案

           1.第二种是ArrayList的构造方法来将HashMap中value添加到collection中。

public class Solution {    public List<List<String>> groupAnagrams(String[] strs) {        Map<String,List<String>>map=new HashMap<>();String num="";for(int i=0;i<strs.length;i++){ char[]ch=strs[i].toCharArray(); Arrays.sort(ch); num=String.valueOf(ch); if(map.containsKey(num)){ map.get(num).add(strs[i]);  }else{ List<String>list=new ArrayList<>(); list.add(strs[i]); map.put(num,list); }      }        //第二种解决方案通过ArrayList的构造方法来将HashMap中value添加到collection中        List<List<String>>li =new ArrayList<>(map.values());          return li;     }      } 


           2.通过LeetCode提交后的详情,很明显运行时间缩短了5ms.












原创粉丝点击