源题目

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 仅包含小写字母

    1. class Solution {
    2. /**
    3. * @param String $s1
    4. * @param String $s2
    5. * @return Boolean
    6. */
    7. function checkInclusion($s1, $s2) {
    8. $len1 = strlen($s1);
    9. $len2 = strlen($s2);
    10. $arr1 = [];
    11. $arr2 =[];
    12. for($i=0; $i<$len1;$i++) {
    13. $arr1[ord($s1[$i])-ord('a')] ++;
    14. $arr2[ord($s2[$i])-ord('a')] ++;
    15. }
    16. if($arr1 == $arr2) return true;
    17. for($i=0;$i+$len1<$len2;$i++){
    18. if($arr2[ord($s2[$i])-ord('a')] < 2){
    19. unset($arr2[ord($s2[$i])-ord('a')]);
    20. }else{
    21. $arr2[ord($s2[$i])-ord('a')]--;
    22. }
    23. $arr2[ord($s2[$i+$len1])-ord('a')] ++;
    24. if($arr1 == $arr2)return true;
    25. }
    26. return false;
    27. }
    28. }