首页 > 代码库 > LeetCode Anagrams My solution

LeetCode Anagrams My solution

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