码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Anagrams My solution

时间:2014-10-31 19:07:14      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   java   for   sp   

Anagrams

 

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.


public class Solution {
    public List<String> anagrams(String[] strs) {
        List<String> result = new ArrayList<String>();
        if (strs == null || strs.length == 0 ) {
            return result;
        }
     HashMap<String,Integer> hmaps = new HashMap<String,Integer>();
     
     for (int i = 0; i < strs.length; i++) {
         String curSort = sortString(strs[i]);
         if (hmaps.containsKey(curSort)) {
           hmaps.put(curSort, hmaps.get(curSort) + 1);   
         } else {
           hmaps.put(curSort, 1); 
         }
     }
     for(int i = 0; i < strs.length; i++) {
         if (hmaps.containsKey(sortString(strs[i])) && hmaps.get(sortString(strs[i])) > 1) {
             result.add(strs[i]);
         }
     }
     return result;
    }
    String sortString(String str) {
        char [] charArr = str.toCharArray();
        Arrays.sort(charArr);
        return Arrays.toString(charArr);
    }
}


LeetCode Anagrams My solution

标签:style   blog   io   color   os   ar   java   for   sp   

原文地址:http://blog.csdn.net/aresgod/article/details/40659193

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!