Problem statement:
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
Solution one: DFS permutation and string match.
This is the third question of leetcode weekly contest 30. I find an approach to solve this problem, it does not accept since of the TLE error.
Like 46. Permutations, I find all permutations and check the string if current permutation exists in the s2. It costs times.
To find all permutations, it costs O(n ^ n).
Since I did not save the code, and a long time after the computation, just brief describe the idea.
Solution two: sliding window.
The problem asks the permutation, it contains two key information: (1) the order does not matter. (2) the letters are consecutive.
Basic above two characteristics, we can use a sliding window to solve this problem, which is different with 424. Longest Repeating Character Replacement and 594. Longest Harmonious Subsequence, the size of sliding window is fixed(the length of s1).
Suppose the length of s1 is k, s2 is n. The basic steps include:
- Initialize the sliding window with first k elements. We should check if letters in current sliding window equal to s1.
- Each time when we moved forward while erasing the element out of the sliding window.
Time complexity is O(k * n).
class Solution { public: bool checkInclusion(string s1, string s2) { if(s1.size() > s2.size()){ return false; } int s1_len = s1.size(); int s2_len = s2.size(); vector<int> s1_cnt(26, 0); vector<int> s2_cnt(26, 0); for(int ix = 0; ix < s1_len; ix++){ s1_cnt[s1.at(ix) - 'a']++; } for(int ix = 0; ix < s2_len; ix++){ s2_cnt[s2.at(ix) - 'a']++; if(ix >= s1_len){ s2_cnt[s2.at(ix - s1_len) - 'a']--; } if(s1_cnt == s2_cnt){ return true; } } return false; } };