Given a string str. The task is to count the words having the same length as str and each letter at the i-th position is either (i-1)-th, i-th, or (i+1)-th position letter of str.
Note: For the first letter consider i-th and (i+1)-th position letter of W. And for last letter consider (i-1)-th and i-th position letter of str.
Input : str = "ab" Output : 4 Words that can be formed: aa, ab, ba, bb. Input : str = "x" Output : 1
For any letter at index i, except first and last letter, there are three possible letter i.e (i-1)th, ith or (i+1)th letter of given words. So, if three of them are distinct, we have 3 possibilities. If two of them are same, we have 2 possibilities. And if all are same we have only 1 possibility.
So, traverse the given words and find the possibility of each letter and multiply them.
Similarly, for first letter check the distinct letter at first and second position. And for last position check the distinct letter at last and second last position.
Below is the implementation of this approach:
Time complexity : O(length of string).
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Get the first letter of each word in a string using regex in Java
- String containing first letter of every word in a given string with spaces
- Find letter's position in Alphabet using Bit operation
- First uppercase letter in a string (Iterative and Recursive)
- Check if the string contains consecutive letters and each letter occurs exactly once
- Number of positions where a letter can be inserted such that a string becomes palindrome
- Get K-th letter of the decoded string formed by repeating substrings
- Count words that appear exactly two times in an array of words
- Count words in a given string
- Count occurrences of a word in string
- Count words present in a string
- Count of words that are present in all the given sentences
- Count palindrome words in a sentence
- Java program to count the characters in each word in a given sentence
- Count the number of words having sum of ASCII values less than and greater than k