leetcode567. Permutation in String

**题目:Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string’s permutations is the substring of the second string.

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:
The input strings only contain lower case letters.
The length of both given strings is in range [1, 10,000].**

首先来分析一下这道题目,本题要求s1的全排列是否在s2当中出现过,这里的全排列需要特别注意,如果你真的将s1的全排列求出,然后再去s2中进行检验那就费了太多力气。实际上要检验s1的全排列,只需要统计s1当中每个字母的出现次数,如果s2中有一段等长字符的每个字母出现次数的统计与s1相同,那就证明s2当中存在s1的全排列。

从这个点出发,然后借助双指针便可以大大提高算法的效率。left、right为双指针,hash_map记录s1中各个字母的出现次数。如果right位置处的字母在s1中出现且统计值大于0,那就将hash_map中该字母的出现次数减1,right右移。如果没有出现,那就将right右移,同时left移动到right位置。如果出现但是在hash_map当中统计值为0,则将left右移直到遇到和此时right处字母相同为止。
以下为具体代码实现:

def checkInclusion(s1,s2):
        if len(s1)>len(s2):
            return False
        hash_={}
        for s in s1:
            if s in hash_:
                hash_[s]+=1
            else:
                hash_[s]=1
        l=len(s1)
        left=0
        right=0
        l_temp=l
        hash_map=hash_.copy()
        while left<len(s2)-l+1:
            if l_temp==0:
                return True
            if s2[right] in hash_:
                if hash_[s2[right]]>0:
                    hash_[s2[right]]-=1
                    right+=1
                    l_temp-=1
                else:
                    while s2[left]!=s2[right]:
                        hash_[s2[left]]+=1
                        left+=1
                        l_temp+=1
                    left+=1
                    right+=1
            else:
                right+=1
                left=right
                l_temp=l
                hash_=hash_map.copy()
        return False    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值