LeetCode: Anagrams 解题报告

时间:2023-03-08 17:12:21

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

Note: All inputs will be in lower-case.

思路:

建Hashtable,用排序过的string作为key,它的anagram作为ArrayList

这道题之前用暴力写的O(N^2)的TLE了,改用Hashtable来写
题目的意思是给一个String数组,找出其中由相同字母组成的单词。
例如:
S = ["abc", "bca", "bac", "bbb", "bbca", "abcb"]
答案为:
["abc", "bca", "bac", "bbca", "abcb"]
只有"bbb"没有相同字母组成的单词。

ref: http://blog.csdn.net/fightforyourdream/article/details/14217985

 public class Solution {
public List<String> anagrams(String[] strs) {
List<String> ret = new ArrayList<String>(); if (strs == null) {
return ret;
} HashMap<String, List<String>> map = new HashMap<String, List<String>>(); int len = strs.length;
for (int i = ; i < len; i++) {
String s = strs[i]; // Sort the string.
char[] chars = s.toCharArray();
Arrays.sort(chars);
String strSort = new String(chars); // Create a ArrayList for the sorted string.
if (!map.containsKey(strSort)) {
map.put(strSort, new ArrayList<String>());
} // Add a new string to the list of the hashmap.
map.get(strSort).add(s);
} // go through the map and add all the strings into the result.
for (Map.Entry<String, List<String>> entry: map.entrySet()) {
List<String> list = entry.getValue(); // skip the entries which only have one string.
if (list.size() == ) {
continue;
} // add the strings into the list.
ret.addAll(list);
} return ret;
}
}

2015.1.3 redo:

 public class Solution {
public List<String> anagrams(String[] strs) {
List<String> ret = new ArrayList<String>();
if (strs == null) {
return ret;
} HashMap<String, List<String>> map = new HashMap<String, List<String>>();
for (int i = 0; i < strs.length; i++) {
String s = strs[i];
char[] chars = s.toCharArray(); Arrays.sort(chars);
String sSort = new String(chars); if (map.containsKey(sSort)) {
map.get(sSort).add(s);
} else {
List<String> list = new ArrayList<String>();
list.add(s);
map.put(sSort, list);
}
} // Bug 1: should use map.entrySet() instead of MAP.
for (Map.Entry<String, List<String>> entry: map.entrySet()) {
List<String> list = entry.getValue();
if (list.size() > 1) {
ret.addAll(list);
}
} return ret;
}
}

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/Anagrams.java