leetcode 76-Minimum Window Substring(hard)

Posted yshi12

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 76-Minimum Window Substring(hard)相关的知识,希望对你有一定的参考价值。

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

 

cases:

when stand on the ith position of S:

1. if the character is not in T, do nothing;

2. if the character is in T:

  start->i contains all characters in T: 

    S[start] not in T or ((frequency of S[start] in start->i) > (frequency of S[start] in T))  start++

    maxlen=max(i-start+1,maxlen), start++

 

use hashmap or int[256/128] to record the number of characters in t, int[] record is better.

 

class Solution {
    public String minWindow(String s, String t) {
        int[] cnum=new int[256];
        int count=t.length();
        for(char c:t.toCharArray()){
            cnum[c]++;
        }
        int start=0;
        int l=0;
        int minlen=Integer.MAX_VALUE;
        for(int r=0;r<s.length();r++){
            if(cnum[s.charAt(r)]>0){
                count--;
            }
            cnum[s.charAt(r)]--;
            if(count==0){
                while(cnum[s.charAt(l)]<0){
                    cnum[s.charAt(l)]++;
                    l++;
                }
                if(r-l+1<minlen){ 
                    minlen=r-l+1;
                    start=l;
                    cnum[s.charAt(l)]++;
                    count++;
                    l++;
                }
            }
        }
        return (minlen== Integer.MAX_VALUE)?"":s.substring(start,start+minlen);
    }
} 

 

注意不要老是笔误s.charAt()写成s.charAt[]!

cnum的index是字母的asc码,不要误写出cnum[l/r]之类,而是cnum[s.charAt(l/r)]!

return的时候不要掉以轻心,不要忘了如果没有满足条件的解的情况!

 

以上是关于leetcode 76-Minimum Window Substring(hard)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode76.Minimum Window Substring

LeetCode in Python 76. Minimum Window Substring

leetcode 76. Minimum Window Substring

Leetcode 76: Minimum Window Substring

leetcode 76-Minimum Window Substring(hard)

leetcode76 Minimum Window Substring