一、题目描述:
给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。
示例1:
输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").
示例2:
输入: s1= "ab" s2 = "eidboaoo"
输出: False
二、思路
每次s2中截取和s1等长的字符串,与s1进行比较,利用数组来统计a-z的数量,辅助比较
三、具体实现
public boolean checkInclusion(String s1, String s2) {
if (s1.length() > s2.length()) {
return false;
}
int[] count = new int[26];
for (int i = 0; i < s1.length(); i++) {
count[s1.charAt(i) - 'a']++;
count[s2.charAt(i) - 'a'] --;
}
if (helper(count)) {
return true;
}
for (int i = s1.length(); i < s2.length(); i++) {
count[s2.charAt(i) - 'a']--;
count[s2.charAt(i - s1.length()) - 'a']++;
if (helper(count)) {
return true;
}
}
return false;
}
public boolean helper(int[] count) {
for (int num : count) {
if (num != 0) {
return false;
}
}
return true;
}