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
第一个字符串排列之一是第二个字符串的子串,这个用哈希表,统计s1字符串里头每个字符出现的次数。在s2里进行滑动比较。两个vector一样就可以出就可以出结果。
代码如下。
class Solution {
public:
bool checkInclusion(string s1, string s2) {
vector<int> t1(26,0);
vector<int> t2(26,0);
int len1 = s1.size();
int len2 = s2.size();
if(len1 > len2)
return false;
for(int i = 0; i < len1; i++)
{
t1[s1[i]-'a']++;
t2[s2[i]-'a']++;
}
if(t1 == t2)
return true;
int j = 0;
for(int i = len1; i<len2; i++)
{
t2[s2[j++]-'a']--;
t2[s2[i]-'a']++;
if(t1 == t2)
return true;
}
return false;
}
};
网友评论