LeetCode 727. Minimum Window Subsequence

原题链接在这里:https://leetcode.com/problems/minimum-window-subsequence/

题目:

Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.

If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.

Example 1:

Input: 
S = "abcdebdde", T = "bde"
Output: "bcde"
Explanation: 
"bcde" is the answer because it occurs before "bdde" which has the same length.
"deb" is not a smaller window because the elements of T in the window must occur in order.

Note:

  • All the strings in the input will only contain lowercase letters.
  • The length of S will be in the range [1, 20000].
  • The length of T will be in the range [1, 100].

题解:

Having a pointer j pointing at T index, when S[i] == T[j], move j++.

When j hits T.length(), then we find a substring candidate. Set a end to mark current position at S.

We need to move i and j back, when j hits 0, now if S.substring(i+ 1, end) length is smaller than minLen, update minWin.

Time Complexity: O(m*n). m = S.length(), n = T.length(). S = "aaaaaa", T = "aas", for each char in S, it is visited 2 * T.length() times.

Space: O(1). 

AC Java:

 1 class Solution {
 2     public String minWindow(String S, String T) {
 3         String minWin = "";
 4         int j = 0;
 5         int minLen = S.length() + 1;
 6         for(int i = 0; i < S.length(); i++){
 7             if(S.charAt(i) == T.charAt(j)){
 8                 j++;
 9             }
10             
11             if(j == T.length()){
12                 int end = i + 1;
13                 j--;
14                 while(j >= 0){
15                     if(T.charAt(j) == S.charAt(i)){
16                         j--;
17                     }
18                     
19                     i--;
20                 }
21                 
22                 if(end - i + 1 < minLen){
23                     minLen = end - i + 1;
24                     minWin = S.substring(i + 1, end);
25                 }
26                 
27                 j++;
28                 i++;
29             }
30         }
31         
32         return minWin;
33     }
34 }

类似Number of Longest Increasing SubsequenceMinimum Window Substring.

上一篇:[BZOJ1396] 识别子串 - 后缀自动机,线段树


下一篇:如何在Python中加速信号处理