567. 字符串的排列 (滑动窗口)

 

给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。

换句话说,第一个字符串的排列之一是第二个字符串的 子串 。

 

示例 1:

输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").

示例 2:

输入: s1= "ab" s2 = "eidboaoo"
输出: False

 

提示:

  • 输入的字符串只包含小写字母
  • 两个字符串的长度都在 [1, 10,000] 之间

 

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        wanted = collections.defaultdict(int)
        cnt_dict = collections.defaultdict(int)
        for c in s1:
            wanted[c]+=1
        
        left = right = valid = 0
        while right < len(s2):
            cur = s2[right]
            if cur in wanted:
                cnt_dict[cur]+=1
                if cnt_dict[cur]==wanted[cur]:
                    valid+=1
            right+=1

            while right-left>=len(s1):
                cur2 = s2[left]
                if valid == len(wanted):
                    return True
                if cur2 in wanted and wanted[cur2]==cnt_dict[cur2]:
                    valid-=1    
                cnt_dict[cur2]-=1
                left+=1
        return False

 

 

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        unordered_map<char,int> need_map, window_map;
        for(auto c : s1) {
            need_map[c]++;
        }
        int left = 0;
        int right = 0;
        int valid = 0;
        while(right < s2.size()) {            
            char cur_c = s2[right];
            
            if (need_map.find(cur_c) != need_map.end()) {
                window_map[cur_c]++;
                if(need_map[cur_c] == window_map[cur_c]) {
                    valid++;
                }
            }
            right++;
            cout << left << "  " << right << endl;
            while(right-left>=s1.size()) { //本题移动 left 缩小窗口的时机是窗口大小大于 t.size() 时,应为排列嘛,显然长度应该是一样的。
                if(valid == need_map.size()) return true; //当发现 valid == need.size() 时,就说明窗口中就是一个合法的排列,所以立即返回 true。
                char cur_c = s2[left];
                if(need_map.find(cur_c) != need_map.end()) {
                    if(need_map[cur_c] == window_map[cur_c]) {
                        valid--;
                    }
                    window_map[cur_c]--;
                }
                left++;
            }
        }
        return false;
    }
};

 

posted @ 2021-05-21 16:28  乐乐章  阅读(62)  评论(0编辑  收藏  举报