源题目
https://leetcode-cn.com/problems/permutation-in-string/
567. 字符串的排列
难度中等408
给你两个字符串 s1 和 s2 ,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,s1 的排列之一是 s2 的 子串 。
示例 1:
输入:s1 = “ab” s2 = “eidbaooo” 输出:true 解释:s2 包含 s1 的排列之一 (“ba”).
示例 2:
输入:s1= “ab” s2 = “eidboaoo” 输出:false
提示:
- 1 <= s1.length, s2.length <= 104
s1 和 s2 仅包含小写字母
class Solution {
/**
* @param String $s1
* @param String $s2
* @return Boolean
*/
function checkInclusion($s1, $s2) {
$len1 = strlen($s1);
$len2 = strlen($s2);
$arr1 = [];
$arr2 =[];
for($i=0; $i<$len1;$i++) {
$arr1[ord($s1[$i])-ord('a')] ++;
$arr2[ord($s2[$i])-ord('a')] ++;
}
if($arr1 == $arr2) return true;
for($i=0;$i+$len1<$len2;$i++){
if($arr2[ord($s2[$i])-ord('a')] < 2){
unset($arr2[ord($s2[$i])-ord('a')]);
}else{
$arr2[ord($s2[$i])-ord('a')]--;
}
$arr2[ord($s2[$i+$len1])-ord('a')] ++;
if($arr1 == $arr2)return true;
}
return false;
}
}