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中,可以有几种方法:
1、将s1全排后逐一与s2的(s2.size() - s1.size())个连续、长度为len1的子串比较。
T = O(n!), M = O(n2)
2、将s1.sort()逐一与s2的(s2.size() - s1.size())个连续、长度为len1的子串s2_str.sort()比较。
T =
O\big(l_1log(l_1)+(l_2-l_1)l_1log(l_1)\big)O(l1log(l1)+(l2−l1)l1log(l1)). M =
O(l_1)O(l1)
3、使用哈希表计算子串中字母出现的频率。
4、使用数组计算子串中字母出现的频率。
① 以“滑动窗口”更新数组,比较时比较整个数组,我的代码里使用vector<int>(26,0) c1为基准,s1中出现的字符在c1里对应的位置上+1,s2的子串中出现的字符在对应位置上-1,若计算结果与vector<int>(26,0)相等,则找到要求的子串,否则窗口向后移动一位,加回窗口开头的前一位:c1[int(s2[i - 1]-'a')],减去窗口的新尾部c1[int(s2[i + len1 - 1]-'a')]。
② 以“最佳滑动窗口”更新数组,用count存储26个字母中s1和s2子列中出现的频度相同的字母的数量,count = 26时返回true。
下面是我的代码:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
int len1 = s1.size(), len2 = s2.size();
if (len1 > len2) {
return false;
}
if (len1 == 0) {
return true;
}
vector<int> c1(26, 0), c2(26, 0);
for (auto c : s1) { // 计算s1频度
c1[int(c-'a')]++;
}
for (int i = 0; i <= (len2 - len1); i++) {
if (i == 0) {
for (int j = 0; j < len1; j++) {
c1[int(s2[j + i]-'a')]--;
}
}
else {
c1[int(s2[i - 1]-'a')]++;
c1[int(s2[i + len1 - 1]-'a')]--;
}
if (c1 == c2) {
return true;
}
// for (auto c : c2) { // 计算s1频度
// cout << c << " ";
// }
// cout << endl;
}
return false;
}
};
附上平台上运行时为0ms的代码:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
if (s1.size() > s2.size()) {
return 0;
}
vector<int> m1(26,0), m2(26,0);
int same = 0;
int cnt = 0;
for (int i = 0; i < s1.size(); i++) {
m1[s1[i] - 'a']++;
m2[s2[i] - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (m1[i] == m2[i]) {
same++;
}
}
for (int i = s1.size(); i < s2.size(); i++) {
if (same == 26) {
return true;
}
char l = s2[i - s1.size()] - 'a';
char r = s2[i] - 'a';
m2[l]--;
if (m1[l] == m2[l]) {
same++;
} else if (m1[l] == m2[l] + 1) { // 在修改的字母上,如果修改前字母频度
// 与s1的相同,即该字母的频度对same有贡献,
// 这次修改就会破坏他的贡献,即修改后字母频度
// 与s1不同,same要-1。
same--;
}
m2[r]++;
if (m1[r] == m2[r]) {
same++;
} else if (m1[r] == m2[r] - 1) { // 同理。
same--;
}
}
return same == 26;
}
};