LeetCode Group Anagrams

Description:

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

Solution:

The description didn't tell us whether we need to find out all the groups of anagrams, so it is better for us to find them all.

Use HashMap <String, ArrayList<String>> as the data structure. The first String can be a representative for all strings in ArrayList<String>, but it is sorted by all chars in it.

Scan all string array. Everytime we meet a string, we turn it into char[] array, then sort it, then turn this char[] array into new string, and use it as a key to search in the HashMap.

After scanning the string array, we then scan the HashMap. If the the size of value ArrayList<String> is bigger than 1, then all strings in this arraylist are anagrams.

import java.util.*;

public class Solution {
	ArrayList<String> list = new ArrayList<String>();
	TreeMap<String, ArrayList<String>> map = new TreeMap<String, ArrayList<String>>();

	public List<String> anagrams(String[] strs) {
		int len = strs.length;

		String str;
		char[] chArray;
		ArrayList<String> temp;
		for (int i = 0; i < strs.length; i++) {
			str = strs[i];
			chArray = str.toCharArray();
			Arrays.sort(chArray);
			str = new String(chArray);

			if (map.containsKey(str)) {
				temp = map.get(str);
				temp.add(strs[i]);
				map.put(str, temp);
			} else {
				temp = new ArrayList<>();
				temp.add(strs[i]);
				map.put(str, temp);
			}
		}

		for (ArrayList<String> l : map.values()) {
			if (l.size() > 1) {
				list.addAll(l);
			}
		}

		return list;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值