patternjavaMinor
Find the longest unique string in the input list
Viewed 0 times
uniquetheinputfindlistlongeststring
Problem
Given a list, find the longest non-repeating (in other words I mean unique) string in the input list. Looking for code review, pointers on best practices, optimizations etc.
public final class LongestUniqueWord {
/*
* do not initialize this class
*/
private LongestUniqueWord( ) {}
/**
* Returns the longest non-repeating(unique) word in the list.
* If each word repeats then return null.
*
*
* @param words the list of words of a news paper.
* @return the longest unique word.
* @throws IllegalArgumentException if input size is 0.
* @throws NPE if the input is null.
*/
public static String longestUniqueWord (List words) {
if (words.size() == 0) throw new IllegalArgumentException("The array should not be empty.");
final Map uniqueWords = new HashMap();
for (String word : words) {
if (uniqueWords.containsKey(word)) {
uniqueWords.put(word, false);
} else {
uniqueWords.put(word, true);
}
}
int maxLength = 0;
String longestUniqueWord = null;
for (Entry entry : uniqueWords.entrySet()) {
if (entry.getValue() && entry.getKey().length() > maxLength) {
longestUniqueWord = entry.getKey();
maxLength = longestUniqueWord.length();
}
}
return longestUniqueWord;
}
public static void main(String[] args) {
List newsPaper = new ArrayList();
newsPaper.add("Jack");
newsPaper.add("In");
newsPaper.add("In");
newsPaper.add("The");
newsPaper.add("The");
newsPaper.add("Box");
System.out.println("Expected: Jack, Actual: " + longestUniqueWord(newsPaper));
newsPaper.add("Jack");
System.out.println("Expected: Box, Actual: " + longestUniqueWord(newsPaper));
}
}Solution
I'm on my phone so can only give pointers.
Next sort those entries by their keys (word length) in reverse and pull the first word from the first set.
Note that you may end up with ties of same-length words. The standard set will return an undefined "first" word. That may be okay.
- In the first loop you can use
Map.getand switch on its value:
null: putTrueand add towordsByLength
True: putFalseand remove fromwordsByLength
False: do nothing
Map> wordsByLength tracks unique word sets, one per word length. It maps word length to a set of unique words. Whenever a new word appears in 1 above, add it to the set. When it is seen again for the first time in 2, remove it.Next sort those entries by their keys (word length) in reverse and pull the first word from the first set.
Note that you may end up with ties of same-length words. The standard set will return an undefined "first" word. That may be okay.
Context
StackExchange Code Review Q#39933, answer score: 2
Revisions (0)
No revisions yet.