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
第一個(gè)字符串排列之一是第二個(gè)字符串的子串,這個(gè)用哈希表,統(tǒng)計(jì)s1字符串里頭每個(gè)字符出現(xiàn)的次數(shù)腌逢。在s2里進(jìn)行滑動(dòng)比較看峻。兩個(gè)vector一樣就可以出就可以出結(jié)果怨绣。
代碼如下迎罗。
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;
}
};