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

Anagrams

时间:2014-09-28 19:10:56      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

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

Note: All inputs will be in lower-case.

<pre name="code" class="java">public class Solution {
	public List<String> anagrams(String[] strs) {
		Map<String, Integer> map = new HashMap<>();
		List<String> res = new ArrayList<String>();
		if (strs.length == 0) {
			return res;
		}
		for (int i = 0; i < strs.length; i++) {
			char[] c = strs[i].toCharArray();
			Arrays.sort(c);
			String s = Arrays.toString(c);
			if (!map.containsKey(s)) {
				map.put(s, 1);
			} else {
				map.put(s, map.get(s) + 1);
			}

		}
		for (int i = 0; i < strs.length; i++) {
			char[] c = strs[i].toCharArray();
			Arrays.sort(c);
			String s = Arrays.toString(c);
			if (map.containsKey(s) && map.get(s) >= 2) {
				res.add(strs[i]);
			}
		}
		return res;
	}
}



Anagrams

标签:java   leetcode   

原文地址:http://blog.csdn.net/guorudi/article/details/39643541

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