使用滑动窗口算法求解该问题答案:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
unordered_map<char,int> need,window;
//构建需要匹配的字符map
for(auto c:s1) need[c] += 1;
int left = 0,right = 0,match_cnt = 0;
while(right < s2.size()){
char c = s2[right];
right++;
if(need.count(c))
{
window[c] += 1;
//已包含s1的全部字符c
if(window[c] == need[c])
match_cnt += 1;
}
//当窗口中字符长度恰好等于s1长度
while(right - left == s1.size()) {
//全部匹配,返回true
if(match_cnt == need.size())
return true;
char c = s2[left];
//左侧边界右移,等待right右移后继续while判断
left++;
if(need.count(c))
{
if(window[c] == need[c])
match_cnt -= 1;
window[c] -= 1;
}
}
}
return false;
}
};
运行效率:
Runtime: 16 ms, faster than 43.98% of C++ online submissions for Permutation in String.
Memory Usage: 7.3 MB, less than 67.50% of C++ online submissions for Permutation in String.