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

[leetcode] Anagrams

时间:2014-06-27 11:34:57      阅读:641      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   java   http   tar   

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

Note: All inputs will be in lower-case.

https://oj.leetcode.com/problems/anagrams/

思路:anagram的题目,CC150也有,如何判断是anagram,一种是用hashmap存字符数来判断,另一种是排序后字符相同来判断。这个题目采用排序后的字符作为hashmap的key,是anagram的都归为一组。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class Solution {
	public ArrayList<String> anagrams(String[] strs) {
		if (strs == null)
			return null;
		ArrayList<String> res = new ArrayList<String>();
		HashMap<String, ArrayList<String>> group = new HashMap<String, ArrayList<String>>();

		for (String each : strs) {
			char[] tmp = each.toCharArray();
			Arrays.sort(tmp);
			String key = new String(tmp);
			if (group.containsKey(key)) {
				group.get(key).add(each);
			} else {
				ArrayList<String> newList = new ArrayList<String>();
				newList.add(each);
				group.put(key, newList);
			}

		}

		for (String each : group.keySet()) {
			if (group.get(each).size() > 1) {
				res.addAll(group.get(each));
			}
		}

		return res;

	}

	public static void main(String[] args) {
		System.out.println(new Solution().anagrams(new String[] { "abc", "acb",
				"cba", "aaa", "bb", "bb" }));
	}

}

参考:

http://blog.csdn.net/linhuanmars/article/details/21664747

[leetcode] Anagrams,布布扣,bubuko.com

[leetcode] Anagrams

标签:class   blog   code   java   http   tar   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810765.html

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