1. 程式人生 > 實用技巧 >Leetcode-最小覆蓋子串

Leetcode-最小覆蓋子串

題目描述
給你一個字串 s 、一個字串 t 。返回 s 中涵蓋 t 所有字元的最小子串。如果 s 中不存在涵蓋 t 所有字元的子串,則返回空字串 "" 。
注意:如果 s 中存在這樣的子串,我們保證它是唯一的答案。

示例 1:
輸入:s = "ADOBECODEBANC", t = "ABC"
輸出:"BANC"
示例 2:
輸入:s = "a", t = "a"
輸出:"a"

思路:雜湊表+滑動視窗

#include <iostream>
#include <vector>
#include <map>
#include <climits>


using namespace std;


class Solution {
public:
    string minWindow(string s, string t) {

    	map<char, int> t_map;
    	map<char, int> s_map;

    	for(auto item:t)
    		t_map[item]++;

    	int left = 0;
    	int right = 0;
    	int target_left_loc = -1;
    	int target_right_loc = 0;

    	int mininim_valid_length = INT_MAX;
    	int matched = 0;

    	while (left<=right && right<s.length()){
    		char s_c = s[right];
    		s_map[s_c]++;

    		if(t_map.count(s_c)!=0 && s_map[s_c]==t_map[s_c])
    			matched += t_map[s_c];

    		while(left<=right && matched == t.length()){
    			int curr_valid_length = right - left + 1;
    			if(curr_valid_length < mininim_valid_length){
    				mininim_valid_length = curr_valid_length;
    				target_left_loc = left;
    				target_right_loc = right;
    			}

    			s_c = s[left];
    			if(t_map.count(s_c)!=0){
    				s_map[s_c]--;
    				if(s_map[s_c] < t_map[s_c])
    					matched -= t_map[s_c];
    			}

    		left++;
    		
    		}
    		right++;
    	}

    	if(target_left_loc <= target_right_loc && target_left_loc!=-1){
    		string res = "";
    		for(int i=target_left_loc; i<=target_right_loc; i++)
    			res += s[i];
    		return res;
    	}else
    		return "";
    }
};

int main(int argc, char const *argv[]){
	string test_s = "a";
	string test_t = "a";

	Solution solu;
	cout<<solu.minWindow(test_s, test_t)<<endl;

	return 0;
}