Description
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string’s permutations is the substring of the second string.
Example 1:
Input:
s1 = "ab" s2 = "eidbaooo"
Output:
True
Explanation:
s2 contains one permutation of s1 ("ba").
Example 2:
Input:
s1= "ab" s2 = "eidboaoo"
Output:
False
Note:
- The input strings only contain lower case letters.
- The length of both given strings is in range [1, 10,000].
分析
题目的意思是:给定字符串s1和s2,判断s1是否是s2子串的一个排列。
- 用滑动窗口的方法,使用一个哈希表配上双指针来做。先统计s1中字符的出现次数,然后遍历s2中的字符,对于每个遍历到的字符,我们在哈希表中对应的字符次数减1。
- 如果次数次数小于0了,说明该字符在s1中不曾出现,或是出现的次数超过了s1中的对应的字符出现次数,那么我们此时移动滑动窗口的左边界,对于移除的字符串,哈希表中对应的次数要加1。
- 如果此时次数不为0,说明该字符不在s1中,继续向右移,直到更新后的次数为0停止,此时到达的字符是在s1中的。
- 如果次数大于等于0了,我们看此时窗口大小是否为s1的长度,若二者相等,由于此时窗口中的字符都是在s1中存在的字符,而且对应的次数都为0了,说明窗口中的字符串和s1互为全排列,返回true即可。
C++实现
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int n1=s1.size();
int n2=s2.size();
int left=0;
vector<int> m(128);
for(char ch:s1) ++m[ch];
for(int right=0;right<n2;right++){
m[s2[right]]--;
if(m[s2[right]]<0){
while (++m[s2[left++]] != 0) {}
}else if(right-left+1==n1) return true;
}
return n1==0;
}
};
Python实现
下面用python来实现一个比较简单的,也是滑动窗口的方法。
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1)>len(s2):
return False
s1_counter = Counter(s1)
window_counter = Counter(s2[:len(s1)])
if s1_counter==window_counter:
return True
for i in range(len(s1),len(s2)):
window_counter[s2[i]]+=1
window_counter[s2[i-len(s1)]]-=1
if window_counter[s2[i-len(s1)]]==0:
del window_counter[s2[i-len(s1)]]
if window_counter==s1_counter:
return True
return False