567. Permutation in String
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:
1. The input strings only contain lower case letters.
2. The length of both given strings is in range [1, 10,000].
Approach
- 给你S1和S2字符串,问你S2是否包含S1的全排列中的一个。题目不难,一开始窝想到的是暴力解法,保存S1所有的全排列,然后去枚举S1的字符串进行匹配,然后我发现当字符串长度才10的时候全排列数量上千了,这样不仅爆内存还超时。然后我换另一种思路,他说全排列的一种可能,那么我就对S1进行映射,然后去枚举S1的字符串进行匹配,确实可行,不过速度有点慢60ms。
Code
class Solution {
public:
bool isvalid(vector<int> let, string &str) {
for (int i = 0; i < str.size(); i++) {
int index = str[i] - 'a';
let[index]--;
if (let[index] < 0)return false;
}
return true;
}
bool checkInclusion(string s1, string s2) {
vector<bool>letter(26, false);
vector<int> let(26, 0);
for (int i = 0; i < s1.size(); i++) {
letter[s1[i] - 'a'] = true;
let[s1[i] - 'a']++;
}
for (int i = 0; i < s2.size(); i++) {
if (letter[s2[i] - 'a']) {
string str = s2.substr(i, s1.size());
if (str.size() < s1.size())return false;
if (isvalid(let, str))return true;
}
}
return false;
}
};
Again
- 看到某位大神的播客,深受启发,用滑动窗口的思想,维护S1长度的S2的子字符串,这样省去我上次代码提取字符串的过程,这样时间就大大缩短,而且代码也简洁。4ms
Code
class Solution {
public:
bool checkInclusion(string s1, string s2) {
vector<int>letters1(26, 0);
vector<int>letters2(26, 0);
for (int i = 0; i < s1.size(); i++) {
letters1[s1[i] - 'a']++;
letters2[s2[i] - 'a']++;
}
if (letters1 == letters2)return true;
for (int i = s1.size(); i < s2.size(); i++) {
letters2[s2[i] - 'a']++;
letters2[s2[i - s1.size()] - 'a']--;
if (letters1 == letters2)return true;
}
return false;
}
};