1. 程式人生 > >leetcode 76-Minimum Window Substring(hard)

leetcode 76-Minimum Window Substring(hard)

hashmap r+ con toc return solution nothing position r++

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)