【leetcode-49】Anagrams(java)

问题描述:
Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

首先,先明白什么叫anagrams,比如eat\ate\tea,这三种,字符一样,但是顺序不同,就叫anagrams。

代码如下:

     public ArrayList<String> anagrams(String[] strs) {
         //key:SortedStr value:ArrayListStr
         HashMap<String, ArrayList<String>> maps = new HashMap<String, ArrayList<String>>();
         ArrayList<String> result = new ArrayList<String>();

         char[] tmpChar;
         String tmpStr;
         ArrayList<String> tmpArrayList;
         for(int i = 0;i<strs.length;i++){
             tmpChar = strs[i].toCharArray();
             Arrays.sort(tmpChar);
             tmpStr = new String(tmpChar);

             if(maps.containsKey(tmpStr)){
                 tmpArrayList = maps.get(tmpStr);
                 tmpArrayList.add(strs[i]);
             }else {
                ArrayList<String> strings = new ArrayList<String>();
                strings.add(strs[i]);
                maps.put(tmpStr, strings);
            }
         }
         Set<String> sets = maps.keySet();

         for(String str:sets){
             if((tmpArrayList=maps.get(str)).size()>1)
                 result.addAll(tmpArrayList);
         }
         return result;
     }
阅读更多
文章标签: leetcode 算法
个人分类: leetcode
上一篇[leetcode91]Restore IP Addresses(java)
下一篇[leetcode-59]spiral matrixII(java)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭