Friday, May 11, 2018

First Unique Word in a Book


Problem : Find the first unique word in entire book .
Solution:

import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Random;
import java.util.stream.Stream;

public class UniqueWordInBook {

static String [] words = {"find","the","first","unique","word","in","entire","book"};
public static void main(String[] args) {
LinkedHashMap wordsVisited = new LinkedHashMap<>();

Random rand = new Random();
Stream stringStream = rand.ints(1, 500).limit(8).mapToObj(i->words[i%(words.length-1)]);
stringStream.forEach(str -> {
System.out.println(str);
if(wordsVisited.containsKey(str)) {
wordsVisited.remove(str);
wordsVisited.put(str, true);
} else {
wordsVisited.put(str, false);
}
});
Entry uniqEntry = wordsVisited.entrySet().iterator().next();
if(!uniqEntry.getValue()) {
System.out.println("First unique word : " + uniqEntry.getKey());
} else {
System.out.println("Not present");
}
}

}

This solution can be used to find the first unique char present in a String.

No comments: