class Solution { public int longestValidSubstring(String word, List<String> forbiddenWords) { // Create a HashSet to efficiently store the forbidden words for quick lookups. Set<String> forbiddenSet = new HashSet<>(forbiddenWords); // Initialize a variable to keep track of the maximum valid substring length found so far. int maxLength = 0; // Initialize the left pointer for the two-pointer approach. int left = 0; // Iterate through each character in the word using the right pointer. for (int right = 0; right < word.length(); right++) { // Get the current substring between the left and right pointers. String currentSubstring = word.substring(left, right + 1); // If the current substring is forbidden, move the left pointer to the right // until the substring is no longer forbidden, to find the next potential valid substring. while (forbiddenSet.contains(currentSubstring)) { left++; currentSubstring = word.substring(left, right + 1); } // Calculate the length of the current valid substring and update maxLength if needed. maxLength = Math.max(maxLength, right - left + 1); } // Return the maximum valid substring length found. return maxLength; } }