Part (a)
/** Constructs a map from words in which the keys are key strings and the
* value associated with a key string is the set of anagrams having that key string.
* Postcondition: each entry of words is contained in an anagram set
* @param words a list of strings to be grouped into anagram sets
* Precondition: words.size() > 0
*/
public AnagramGrouper(List<String> words)
{
groups = new HashMap<String, HashSet<String>>();
for (String word : words)
{
String key = createKeyString(word);
if (groups.containsKey(key))
groups.get(key).add(word);
else
{
HashSet<String> newSet = new HashSet<String>();
newSet.add(word);
groups.put(key, newSet);
}
}
}
Part (b)
/** @return a set of all anagram sets of largest size in this AnagramGrouper
*/
public HashSet<HashSet<String>> findLargestSets()
{
int maxSize = 0;
for (String key : groups.keySet())
{
int size = groups.get(key).size();
if (size > maxSize)
maxSize = size;
}
HashSet<HashSet<String>> maxSets = new HashSet<HashSet<String>>();
for (String key : groups.keySet())
{
HashSet<String> set = groups.get(key);
if (set.size() == maxSize)
maxSets.add(set);
}
return maxSets;
} 1
Notes:
- There is a solution with only one loop —
...
for (String key : groups.keySet())
{
HashSet<String> set = groups.get(key);
int size = set.size();
if (size > maxSize)
{
maxSets = new HashSet<HashSet<String>>();
maxSize = size;
}
if (size == maxSize)
maxSets.add(set);
}
...
— but this version gives a lot of work to the garbage collector.
|