Count similar words in a given array

Given an array of strings, write a program to count all the similar words. 

Similar words: Two words are similar if

  1. Has spaces in-between or at the end. Ex: “Apple” and ” A pp le” are similar.
  2. Has upper or lower cases. Ex: “APPle” and “apple” are similar.
  3. Has special characters. Ex: “app%^L&e” and “@@apple” are similar.

Example:;

input = ["Apple", "Bat", "apple", "A%^%ppLE", "BA  T", " C A T", "cAt "]
Output: 
apple -- 3
bat -- 2
cat -- 2

Approach: Use Map

Maintain a map which contains the count of each word(word as key and its count as value) and below making an entry into the map do the steps below –

  • Convert the word to lowercase ( to ignore cases).
  • Trim the word from the ends.
  • Remove all the spaces in between.
  • Remove all the special characters.

Once the array is iterated, print the map.

Time Complexity: O(N), Space Complexity: O(N)

Complete Code:

Output:

apple -- 3
bat -- 2
cat -- 2