LeetCode 727. Minimum Window Subsequence

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

题目:

Given strings s1 and s2, return the minimum contiguous substring part of s1, so that s2 is a subsequence of the part.

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

Example 1:

Input: s1 = "abcdebdde", s2 = "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 s2 in the window must occur in order.

Example 2:

Input: s1 = "jmeqksfrsdcmsiwvaovztaqenprpvnbstl", s2 = "u"
Output: ""

Constraints:

  • 1 <= s1.length <= 2 * 104
  • 1 <= s2.length <= 100
  • s1 and s2 consist of lowercase English letters.

题解:

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

When j hits s2.length(), then we find a substring candidate.

Set a end to mark end of this candidate.

We need to move i and j back to find the start of the candidate.

When j hits 0, now i + 1 is the start of the candidate.

if s1.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 s1, String s2) {
 3         int start = -1;
 4         int s1Len = s1.length();
 5         int minLen = s1Len + 1;
 6         int j = 0;
 7         for(int i = 0; i < s1Len; i++){
 8             if(s1.charAt(i) == s2.charAt(j)){
 9                 j++;
10             }
11 
12             if(j == s2.length()){
13                 int end = i + 1;
14                 j--;
15                 while(j >= 0){
16                     if(s1.charAt(i) == s2.charAt(j)){
17                         j--;
18                     }
19                     i--;
20                 }
21 
22                 i++;
23                 j++;
24                 if(end - i < minLen){
25                     minLen = end - i;
26                     start = i;
27                 }
28             }
29         }
30 
31         return start == -1 ? "" : s1.substring(start, start + minLen);
32     }
33 }

类似Number of Longest Increasing SubsequenceMinimum Window Substring.

posted @ 2019-12-28 13:54  Dylan_Java_NYC  阅读(489)  评论(0编辑  收藏  举报