[220211] Permutation in String

这篇博客讨论了一种算法问题,即如何检查一个字符串s2是否包含字符串s1的排列作为子串。解决方案中使用了Python的Counter类来创建字符计数,并通过滑动窗口的方法遍历s2,判断每个窗口内的字符计数是否与s1相同。如果找到匹配的窗口,则返回True,否则返回False。
摘要由CSDN通过智能技术生成

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

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

from collections import Counter


class Solution:
    def checkInclusion(self, s1, s2):
        
        # base case
        if len(s1) > len(s2):
            return False
        
        c = Counter(s1)
        
        # sliding window with length == len(s1)
        for i in range(len(s2) - len(s1) + 1):
            if Counter(s2[i:i+len(s1)]) == c:
                return True
        return False

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值