[leetcode] 567. Permutation in String

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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

Note:

  1. The input strings only contain lower case letters.
  2. The length of both given strings is in range [1, 10,000].

分析

题目的意思是:给定字符串s1和s2,判断s1是否是s2子串的一个排列。

  • 用滑动窗口的方法,使用一个哈希表配上双指针来做。先统计s1中字符的出现次数,然后遍历s2中的字符,对于每个遍历到的字符,我们在哈希表中对应的字符次数减1。
  • 如果次数次数小于0了,说明该字符在s1中不曾出现,或是出现的次数超过了s1中的对应的字符出现次数,那么我们此时移动滑动窗口的左边界,对于移除的字符串,哈希表中对应的次数要加1。
  • 如果此时次数不为0,说明该字符不在s1中,继续向右移,直到更新后的次数为0停止,此时到达的字符是在s1中的。
  • 如果次数大于等于0了,我们看此时窗口大小是否为s1的长度,若二者相等,由于此时窗口中的字符都是在s1中存在的字符,而且对应的次数都为0了,说明窗口中的字符串和s1互为全排列,返回true即可。

C++实现

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        int n1=s1.size();
        int n2=s2.size();
        int left=0;
        vector<int> m(128);
        for(char ch:s1) ++m[ch];
        for(int right=0;right<n2;right++){
            m[s2[right]]--;
            if(m[s2[right]]<0){ 
                while (++m[s2[left++]] != 0) {}
            }else if(right-left+1==n1) return true;
        }
        return n1==0;
    }
};

Python实现

下面用python来实现一个比较简单的,也是滑动窗口的方法。

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        
        if len(s1)>len(s2):
            return False
        s1_counter = Counter(s1)
        
        window_counter = Counter(s2[:len(s1)])
        if s1_counter==window_counter:
            return True

        for i in range(len(s1),len(s2)):
            window_counter[s2[i]]+=1
            window_counter[s2[i-len(s1)]]-=1
            if window_counter[s2[i-len(s1)]]==0:
                del window_counter[s2[i-len(s1)]]
            if window_counter==s1_counter:
                return True
        return False

参考文献

[LeetCode] Permutation in String 字符串中的全排列

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值