1. 程式人生 > >LeetCode-76-Minimum Window Substring

LeetCode-76-Minimum Window Substring

兩個 字符串問題 映射 bsp rac eba over n) you

算法描述:

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).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

解題思路:子字符串問題,可以采用強大的滑動窗口方法解決。首先用map對字符串進行映射,並用兩個指針分別指向窗口左邊和右邊,通過不斷的滑動兩個指針實現對窗口內字符的操作。

    string minWindow(string s, string t) {
        string res = "";
        unordered_map<char,int> map;
        for(char c:t) map[c]++;
        int left=0;
        int right = 0;
        int distance = INT_MAX;
        
int count = t.size(); int head = 0; while(right < s.size()){ if(map[s[right++]]-- >0) count--; while(count==0){ if(right-left< distance){ head = left; distance = right-head; }
if(map[s[left++]]++ ==0) count++; } } return distance==INT_MAX?"":s.substr(head,distance); }

LeetCode-76-Minimum Window Substring