You are given a string S of words. Your task is to find the number of palindrome words in the given string S. A word is called palindrome, if it reads the same backwards as forwards.
Note:Words are separated by one or more whitespace characters.
For Example:
For the given string “Madam oyo cat”, “Madam”, and “oyo” are the palindrome words
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then, the T test cases follow.
The first and only line of each test case contains the string S.
Output format:
For each test case, print the number of palindrome words in the given string S in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
0 <= |S| <= 10^5
All the characters of the string S contain whitespace, lowercase, and uppercase English letters only.
Time limit: 1 second
1
Nitin and I are good friends
2
For the first test case, there are 2 palindrome words only i.e “Nitin” and “I”.
2
Madam taught us the level order traversal of a binary tree yesterday
We love coding ninjas
3
0
Traverse the string and for each word, check if it is a palindrome or not.
Steps:
For Checking the word is palindrome or not:
O(N), where N is the length of the given string.
In the worst case, we will be traversing the whole string which takes O(N) time, and checking if each word of the string is palindrome or not takes overall O(N) time throughout the program.
Hence the overall complexity will be O(N).
O(1)
In the worst case, a constant space is required.