|
| 1 | +/** |
| 2 | + * 1639. Number of Ways to Form a Target String Given a Dictionary |
| 3 | + * https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a list of strings of the same length words and a string target. |
| 7 | + * |
| 8 | + * Your task is to form target using the given words under the following rules: |
| 9 | + * - target should be formed from left to right. |
| 10 | + * - To form the ith character (0-indexed) of target, you can choose the kth character of the jth |
| 11 | + * string in words if target[i] = words[j][k]. |
| 12 | + * - Once you use the kth character of the jth string of words, you can no longer use the xth |
| 13 | + * character of any string in words where x <= k. In other words, all characters to the left of |
| 14 | + * or at index k become unusuable for every string. |
| 15 | + * - Repeat the process until you form the string target. |
| 16 | + * |
| 17 | + * Notice that you can use multiple characters from the same string in words provided the |
| 18 | + * conditions above are met. |
| 19 | + * |
| 20 | + * Return the number of ways to form target from words. Since the answer may be too large, return |
| 21 | + * it modulo 109 + 7. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {string[]} words |
| 26 | + * @param {string} target |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var numWays = function(words, target) { |
| 30 | + const MOD = 1e9 + 7; |
| 31 | + const wordLength = words[0].length; |
| 32 | + const targetLength = target.length; |
| 33 | + const charCounts = Array(wordLength).fill().map(() => Array(26).fill(0)); |
| 34 | + |
| 35 | + for (const word of words) { |
| 36 | + for (let i = 0; i < wordLength; i++) { |
| 37 | + charCounts[i][word.charCodeAt(i) - 97]++; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + const dp = Array(targetLength + 1).fill().map(() => Array(wordLength + 1).fill(0)); |
| 42 | + dp[0][0] = 1; |
| 43 | + |
| 44 | + for (let i = 0; i <= targetLength; i++) { |
| 45 | + for (let j = 0; j < wordLength; j++) { |
| 46 | + if (i < targetLength) { |
| 47 | + const charIndex = target.charCodeAt(i) - 97; |
| 48 | + dp[i + 1][j + 1] = (dp[i + 1][j + 1] + dp[i][j] * charCounts[j][charIndex]) % MOD; |
| 49 | + } |
| 50 | + dp[i][j + 1] = (dp[i][j + 1] + dp[i][j]) % MOD; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return dp[targetLength][wordLength]; |
| 55 | +}; |
0 commit comments