This post is completed by 6 users
|
Add to List |
516. 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
- Has spaces in-between or at the end. Ex: "Apple" and " A pp le" are similar.
- Has upper or lower cases. Ex: "APPle" and "apple" are similar.
- 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)
Output:
apple -- 3 bat -- 2 cat -- 2