`
hcx2013
  • 浏览: 83344 次
社区版块
存档分类
最新评论

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) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String s : strs) {
        	char[] arr = s.toCharArray();
        	Arrays.sort(arr);
        	String t = new String(arr);
        	if (!map.containsKey(t)) {
        		map.put(t, new ArrayList<String>());
        	}
        	map.get(t).add(s);
        }
        List<String> res = new ArrayList<String>();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        	if (entry.getValue().size() > 1) {
        		res.addAll(entry.getValue());
        	}
        }
        return res;
    }
}

 

11
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics