当前位置:网站首页>Sword finger offer II 014 A sliding window of anagrams in strings

Sword finger offer II 014 A sliding window of anagrams in strings

2022-06-25 17:04:00 Python ml

The finger of the sword Offer II 014. An anamorphic word in a string
The sliding window

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        m,n=len(s1),len(s2)
        if m>n:
            return False
        cnt_s1=Counter(s1)
        for i in range(n-m+1):              # i by 0-n-m
            if Counter(s2[i:i+m])==cnt_s1:     # Excluding the index i+m
                return True
        return False

Double pointer , In process assurance dict[left] to dict[right] Each value in is less than 0, Explain that there are no extra letters or other letters , And [left,right] The length of is just m, Explain that each letter has the same number , Otherwise, in the ++dict[x] The latter must exist dict[x]>0

class Solution {
    
public:
    bool checkInclusion(string s1, string s2) {
    
		int m=s1.length(),n=s2.length();
		vector<int>dict(26);
		for(int i=0;i<m;++i){
    
			--dict[s1[i]-'a'];
		}
		int left=0;
		for(int right=0;right<n;++right){
    
			int x=s2[right]-'a';
			++dict[x];
			while (dict[x]>0){
    
				--dict[s2[left]-'a'];
				++left;
			}
			if(right-left+1==m) return true;
		}
		return false;
    }
};
原网站

版权声明
本文为[Python ml]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251635253439.html