![]() |
VOOZH | about |
You are given a string S of length N and a dictionary arr[] containing K words. In how many ways can you create the string using the words?
Examples:
Input: S = "ababc", K = 4, arr[] = {ab, abab, c, cb}
Output: 2
Explanation: The possible ways are "ab" + "ab" + "c" and "abab" + "c".Input: S = "geeksforgeeks", K = 3, arr[] = {geeks, for, geeks}
Output: 2
Explanation: The possible ways are "geeks" + "for" + "geeks" and "geeks" + "for" + "geeks" .
Approach: To solve the problem, follow the below idea:
The problem can be solved by Dynamic Programming and Tries. We can maintain a dp[] array such that dp[i] stores the number of ways to form the substring S[i...N-1]. We can travverse the string S from right to left and for every index i, dp[i] is the sum of all dp[j + 1] such that S[i...j] is present in the dictionary. In order to check whether dp[i...j] is present in the dictionary or not, we can insert all the words in a trie and mark the ending of each word with a flag. So, for every index i, we iterate j from i to N-1 and if S[i...j] is present in the dictionary, we add dp[j] to dp[i]. After all the iterations, dp[0] will store the answer.
Step-by-Step algorithm:
Below is the implementation of the algorithm:
2
Time complexity: O(N * N + N * K), where N is the number of length of S and K is the number of words in the dictionary.
Auxiliary Space: O(N * K)