LeetCode 2781. Length of the Longest Valid Substring

原题链接在这里:https://leetcode.com/problems/length-of-the-longest-valid-substring/description/

题目:

You are given a string word and an array of strings forbidden.

A string is called valid if none of its substrings are present in forbidden.

Return the length of the longest valid substring of the string word.

A substring is a contiguous sequence of characters in a string, possibly empty.

Example 1:

Input: word = "cbaaaabc", forbidden = ["aaa","cb"]
Output: 4
Explanation: There are 11 valid substrings in word: "c", "b", "a", "ba", "aa", "bc", "baa", "aab", "ab", "abc" and "aabc". The length of the longest valid substring is 4. 
It can be shown that all other substrings contain either "aaa" or "cb" as a substring. 

Example 2:

Input: word = "leetcode", forbidden = ["de","le","e"]
Output: 4
Explanation: There are 11 valid substrings in word: "l", "t", "c", "o", "d", "tc", "co", "od", "tco", "cod", and "tcod". The length of the longest valid substring is 4.
It can be shown that all other substrings contain either "de", "le", or "e" as a substring. 

Constraints:

  • 1 <= word.length <= 105
  • word consists only of lowercase English letters.
  • 1 <= forbidden.length <= 105
  • 1 <= forbidden[i].length <= 10
  • forbidden[i] consists only of lowercase English letters.

题解:

The question is asking for the longest substring with no forbidden word.

Iterate from right to left using index i, and from to right index j, if word[i, j] is forbidden, mark the right position.

Update the result for each index i.

Time Complexity: O(m * maxLen + n * maxLen * maxLen). m = forbidden.size(). n = word.length(). 

Space: O(m * maxLen).

AC Java:

 1 class Solution {
 2     public int longestValidSubstring(String word, List<String> forbidden) {
 3         Set<String> hs = new HashSet<>();
 4         int maxLen = 0;
 5         for(String s : forbidden){
 6             hs.add(s);
 7             maxLen = Math.max(maxLen, s.length());
 8         }
 9 
10         int res = 0;
11         int n = word.length();
12         int right = n - 1;
13         for(int i = n - 1; i >= 0; i--){
14             for(int j = i; j <= Math.min(i + maxLen, right); j++){
15                 if(hs.contains(word.substring(i, j + 1))){
16                     right = j - 1;
17                     break;
18                 }
19             }
20 
21             res = Math.max(res, right - i + 1);
22         }
23 
24         return res;
25     }
26 }

 

posted @ 2024-06-17 13:34  Dylan_Java_NYC  阅读(13)  评论(0编辑  收藏  举报