Monday, June 30, 2014

[Leetcode] Anagrams

Problem

Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case. For example, 
Input: {"abc", "bca", "bac", "bbb", "bbca", "abcb"}
Output: {"abc", "bca", "bac", "bbca", "abcb"}, 
since "bbb" does not have an anagram

Algorithm

When check existing, first consider the hash map. We create a hash map, where 
                                 [key, value] = [a sorted string, list of index whose sorted format equals key]. 
After iterate all strings in input, we build a hash map. If a string has at least anagrams in the input, its value should have at least two elements. We can then iterate the keySet of the hash map, add the index list if its length is larger than 1.

Sort a String

Note, there is no String.sort() method, in order to sort a string

char[] c = str.toCharArray();
Arrays.sort(c);
String sorted = new String(c);

Code



No comments:

Post a Comment