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 email@example.com. 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.
- Print list items containing all characters of a given word
- Reverse words in a given string
- Given a sequence of words, print all anagrams together | Set 1
- Given a sequence of words, print all anagrams together | Set 2
- Count words in a given string
- Print all possible words from phone digits
- Given a binary string, count number of substrings that start and end with 1.
- Recursively print all sentences that can be formed from list of word lists
- Print all words matching a pattern in CamelCase Notation Dictonary
- Longest Common Prefix using Word by Word Matching
- Count number of substrings with exactly k distinct characters
- Count Distinct Subsequences
- Count Substrings with equal number of 0s, 1s and 2s
- Count of distinct substrings of a string using Suffix Trie
- Count characters at same position as in English alphabet