LeetCode 3291: Minimum Number of Valid Strings to Form Target I Solution
Master LeetCode problem 3291 (Minimum Number of Valid Strings to Form Target I), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3291. Minimum Number of Valid Strings to Form Target I
Problem Explanation
Explanation:
To solve this problem, we can iterate through the target string and keep track of the prefixes of words that can form the current substring of the target. We can use dynamic programming to efficiently compute the minimum number of valid strings needed to form the target string.
- Initialize a DP array of size equal to the length of the target string + 1. DP[i] will store the minimum number of valid strings required to form a target substring of length i.
- Initialize DP[0] = 0, as an empty substring requires 0 valid strings.
- Iterate through the target string character by character:
- For each character in the target string, try to match the prefixes of words with the current substring of the target.
- If a prefix matches the current substring, update DP[i] with the minimum of (DP[i], DP[i - prefix.length] + 1) where prefix.length is the length of the matched prefix.
- Finally, return DP[target.length()] if it is not equal to Integer.MAX_VALUE, else return -1. :
Solution Code
class Solution {
public int minNumOfValidStrings(String[] words, String target) {
int n = target.length();
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
for (String word : words) {
if (word.length() <= i && target.substring(i - word.length(), i).equals(word)) {
dp[i] = Math.min(dp[i], dp[i - word.length()] + 1);
}
}
}
return dp[n] != Integer.MAX_VALUE ? dp[n] : -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3291 (Minimum Number of Valid Strings to Form Target I)?
This page provides optimized solutions for LeetCode problem 3291 (Minimum Number of Valid Strings to Form Target I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3291 (Minimum Number of Valid Strings to Form Target I)?
The time complexity for LeetCode 3291 (Minimum Number of Valid Strings to Form Target I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3291 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3291 in Java, C++, or Python.