LeetCode 3292: Minimum Number of Valid Strings to Form Target II

Problem Description

Explanation:

To solve this problem, we can use dynamic programming. We iterate through the target string and try to find valid prefixes from the words array that can form the target string. We maintain a dp array to keep track of the minimum number of valid strings needed to form prefixes of the target string.

Here are the steps:

  1. Initialize a dp array of size target.length() + 1 with all elements set to infinity except dp[0] which is set to 0.
  2. Iterate through the target string and try to form prefixes using words array.
  3. For each position i in the target string, iterate through the words array and check if a valid prefix can be formed by concatenating a word to the current prefix.
  4. Update the dp array with the minimum number of valid strings needed to form the prefix at position i.
  5. Finally, return dp[target.length()] if it is not infinity, otherwise return -1.

Time Complexity: O(n * m) where n is the length of the target string and m is the total number of characters in all words. Space Complexity: O(n) where n is the length of the target string.

:

Solutions

class Solution {
    public int minNumOfStrings(String[] words, String target) {
        int[] dp = new int[target.length() + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;

        for (int i = 0; i < target.length(); i++) {
            for (String word : words) {
                int len = word.length();
                if (i + len <= target.length() && target.substring(i, i + len).equals(word)) {
                    dp[i + len] = Math.min(dp[i + len], dp[i] + 1);
                }
            }
        }

        return dp[target.length()] == Integer.MAX_VALUE ? -1 : dp[target.length()];
    }
}

Loading editor...