LeetCode 2781: Length of the Longest Valid Substring Solution
Master LeetCode problem 2781 (Length of the Longest Valid Substring), a hard 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.
2781. Length of the Longest Valid Substring
Problem Explanation
Explanation
To find the length of the longest valid substring, we can iterate through the string word and check if each substring of word is present in the forbidden list. We can use a sliding window approach to efficiently check for valid substrings. If a substring is valid, we update the length of the longest valid substring found so far.
Algorithm
- Initialize a variable
maxLento store the length of the longest valid substring found so far. - Iterate through each character in the string
word. - For each character, check all substrings starting from that character to the end of the string.
- If a substring is not present in the
forbiddenlist, updatemaxLenif the length of the current substring is greater. - Return
maxLenas the length of the longest valid substring.
Time Complexity
The time complexity of this approach is O(n^3), where n is the length of the string word.
Space Complexity
The space complexity is O(1) as we are not using any additional data structures.
Solution Code
class Solution {
public int longestValidSubstring(String word, String[] forbidden) {
int n = word.length();
int maxLen = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
String sub = word.substring(i, j);
boolean isValid = true;
for (String f : forbidden) {
if (sub.contains(f)) {
isValid = false;
break;
}
}
if (isValid) {
maxLen = Math.max(maxLen, j - i);
}
}
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2781 (Length of the Longest Valid Substring)?
This page provides optimized solutions for LeetCode problem 2781 (Length of the Longest Valid Substring) 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 2781 (Length of the Longest Valid Substring)?
The time complexity for LeetCode 2781 (Length of the Longest Valid Substring) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2781 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2781 in Java, C++, or Python.