Question: **Java 2) Given a sentence, find total number of words as well as the unique words and how many times each unique word occurs. Sample
**Java
2) Given a sentence, find total number of words as well as the unique words and how many times each unique word occurs.
Sample i/p: row row row your boat gently down the stream merrily merrily merrily merrily life is but a dream
Expected output:
total number of words : 18
number of unique words : 13
row : 3
your : 1
boat : 1
gently : 1
down : 1
the : 1
stream : 1
merrily : 4
life : 1
is : 1
but : 1
a : 1
dream : 1
As you get each token, if you haven't seen that token before, count how many times it occurs in the string and print it as output.
To help with identifying if this token has been seen earlier, you can maintain another string that keeps tracks of new tokens - say String uniqueWordList - which is initially empty.
e.g. the first token is "row",
uniqueWordList does not have "row", so we know that this is a new token which means we need to append it to uniqueWordList.
Because it is new, we need to count how many times it appears in the rest of the given string........which means after searching continuously for "row" until the end of sentence, we will be printing "row :3"
Next token is "row".
We check if "row" is in uniqueWordList - it will be there (because when it occurred first time, we realized it was new & we appended).
so we go to next token - which in our case is again "row".
"row" is in unique word list, so we skip to next token.
which is "your"
(at this point remember that uniqueWordList just has one word "row" in it).
"your" is not in uniqueWordList, so we append your to uniqueWordList
now uniqueWordList has "row your"
now check how many times "your" occurs in the given sentence.
it doesn't occur again....so print "your : 1"
process next token which is "boat"....
and so the process continues.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
