727. 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: ""
1 class Solution { 2 public String minWindow(String S, String T) { 3 if (S.isEmpty() || T.isEmpty()) { 4 return ""; 5 } 6 7 int right = 0, minLen = Integer.MAX_VALUE; 8 String result = ""; 9 10 while (right < S.length()) { 11 int tIndex = 0; 12 while (right < S.length()) { 13 if (S.charAt(right) == T.charAt(tIndex)) { 14 tIndex++; 15 } 16 if (tIndex == T.length()) { 17 break; 18 } 19 right++; 20 } 21 22 // if right pointer is over than boundary 23 if (right == S.length()) { 24 break; 25 } 26 27 // use another slow pointer to traverse from right to left until find first 28 // character of T in S 29 int left = right; 30 tIndex = T.length() - 1; 31 while (left >= 0) { 32 if (S.charAt(left) == T.charAt(tIndex)) { 33 tIndex--; 34 } 35 if (tIndex == -1) { 36 break; 37 } 38 left--; 39 } 40 // if we found another subsequence with smaller length, update result 41 if (right - left + 1 < minLen) { 42 minLen = right - left + 1; 43 result = S.substring(left, right + 1); 44 } 45 right = left + 1; 46 } 47 return result; 48 } 49 }