题目:给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。换句话说,第一个字符串的排列之一是第二个字符串的子串。
示例1:
输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").
示例2:
输入: s1= "ab" s2 = "eidboaoo"
输出: False
AC代码,滑动窗口算法:
class Solution {
public boolean checkInclusion(String s1, String s2) {
int i = 0;
int j = 0;
int n_s1 = s1.length();
int n_s2 = s2.length();
int[] counts = new int[26];
for(int x = 0;x < n_s1;++x){
++counts[s1.charAt(x) - 97];
}
int[] temp = new int[26];
int[] index_count = new int[26];
int hasReturn = 0;
while(i <= n_s2 - n_s1 && j < s2.length()){
if(counts[s2.charAt(j) - 97] == 0){
i = ++j;
temp = new int[26];
index_count = new int[26];
hasReturn = 0;
}
else{
int j_index = s2.charAt(j) - 97;
int i_index = s2.charAt(i) - 97;
if(temp[j_index] + 1 >counts[j_index]){
--temp[i_index];
if(temp[i_index] != counts[i_index]){
if(index_count[i_index] == 1){
index_count[i_index] = 0;
hasReturn -= counts[i_index];
}
}
++i;
}
else if(temp[j_index] + 1 == counts[j_index]){
index_count[j_index] = 1;
hasReturn += counts[j_index];
if(hasReturn == n_s1)
return true;
++temp[j_index];
++j;
}
else{
++temp[j_index];
++j;
}
}
}
return false;
}
}
解法2:暴力求解
来源:CSDN
作者:liuliuliudy
链接:https://blog.csdn.net/qq_33607393/article/details/104539254