[leetcode] 567. Permutation in String

题目

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

In other words, return true if one of s1's permutations is the substring of s2.

Example 1:

Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").

Example 2:

Input: s1 = "ab", s2 = "eidboaoo"
Output: false

Constraints:

  • 1 <= s1.length, s2.length <= 10^4
  • s1 and s2 consist of lowercase English letters.

思路

使用字典保存s1中所有字符的数量,使用滑动窗口遍历s2,使用字典保存窗口中的值,当s1字典和s2字典相同时,则返回true,否则在遍历结束后返回false。

代码

python版本:

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        cnt=Counter(s1)
        l1=len(s1)
        for i,v in enumerate(s2):
            if v in cnt:
                cnt[v]-=1
            if i-l1>=0 and s2[i-l1] in cnt:
                cnt[s2[i-l1]]+=1
            if all([i==0 for i in cnt.values()]):
                return True
        return False
posted @ 2022-02-27 01:52  frankming  阅读(19)  评论(0编辑  收藏  举报