1169 · Permutation in String
Algorithms
Medium
Description
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.
The input strings only contain lower case letters.
The length of both given strings is in range [1, 10,000].
Example
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
Tags
Company
Microsoft
Related Problems
32
Minimum Window Substring
Medium
647
Find All Anagrams in a String
Medium
解法1:把s1里面的permutation都找出来,然后看是不是在s2里面,这个应该是O(2^m * n),其中m和n分别为s1和s2的长度。肯定超时,不管怎么剪枝都没用。
class Solution {
public:
/**
* @param s1: a string
* @param s2: a string
* @return: if s2 contains the permutation of s1
*/
bool checkInclusion(string &s1, string &s2) {
vector<int> visited(s1.size(), false);
string sol = "";
return helper(s1, visited, sol, s2);
}
private:
bool helper(string &s1, vector<int> &visited, string &sol, string &s2) {
if (sol.size() == s1.size()) {
if (s2.find(sol) != string::npos) return true;
return false;
}
for (int i = 0; i < s1.size(); i++) {
if (visited[i]) continue;
visited[i] = true;
sol = sol + s1[i];
if (helper(s1, visited, sol, s2)) return true;
sol.pop_back();
visited[i] = false;
}
return false;
}
};
解法2:滑动窗口法。s2从左到右移动,每s1长度的字符就比较freq1和freq2。时间复杂度O(n)。其中n为s2的长度。但实际上还要乘以128这个常数。这个应该不是最优。
class Solution {
public:
/**
* @param s1: a string
* @param s2: a string
* @return: if s2 contains the permutation of s1
*/
bool checkInclusion(string &s1, string &s2) {
int len1 = s1.size();
int len2 = s2.size();
if (len1 > len2) return false;
vector<int> freq1(128, 0), freq2(128, 0);
for (int i = 0; i < len1; i++) {
freq1[s1[i]]++;
freq2[s2[i]]++;
}
if (freq1 == freq2) return true;
for (int i = len1; i < len2; i++) {
freq2[s2[i]]++;
freq2[s2[i - len1]]--;
if (freq1 == freq2) return true;
}
return false;
}
};
解法3: 同向双指针,时间复杂度O(n), n为s2长度。
class Solution {
public:
/**
* @param s1: a string
* @param s2: a string
* @return: if s2 contains the permutation of s1
*/
bool checkInclusion(string &s1, string &s2) {
vector<int> freq(128, 0);
int len1 = s1.size(), len2 = s2.size();
int count = len1, left = 0, j = 0;
for (auto s : s1) freq[s]++;
for (int i = 0; i < len2; i++) {
j = max(i, j); //i is left, j is right
while (count > 0 && j < len2) {
if (freq[s2[j]] > 0) count--;
freq[s2[j]]--;
j++;
}
if (count == 0 && j - i == len1) return true; //the window is just right
if (freq[s2[i]] == 0) count++; // s2[i] is in s1
freq[s2[i]]++;
}
return false;
}
};
注意: