问题描述:
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.
示例:
Input:s1 = "ab" s2 = "eidbaooo" Output:True Explanation: s2 contains one permutation of s1 ("ba").
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].
问题分析:
以上问题可采用滑动窗口法求解。
过程详见代码:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
vector<int> map(26, 0);
int m = s1.length(), n = s2.length();
if (m > n) return false;
for (int i = 0; i < m; i++)
{
map[s2[i] - 'a']++;
map[s1[i] - 'a']--;
}
if (allZero(map)) return true;
for (int i = m; i < n; i++)
{
map[s2[i] - 'a']++;
map[s2[i - m] - 'a']--;
if (allZero(map)) return true;
}
return false;
}
bool allZero(vector<int> map) {
for (int i = 0; i < 26; i++) {
if (map[i] != 0) return false;
}
return true;
}
};