LeetCode 567.字符串的排列

给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。

示例1:
输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").

示例2:
输入: s1= "ab" s2 = "eidboaoo"
输出: False

注意:
输入的字符串只包含小写字母
两个字符串的长度都在 [1, 10,000] 之间

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        """
        分析:如果两个字符串的元素组成相同,则排列存在相同;
             问题转化成:找s2中是否有子串与s1的元素组成相同,对于子串问题,这里可以使用双指针
             另外要注意把指针移动位置分析清楚
        """
        import numpy as np
        s1_lookup = np.array([0] * 26)
        s2_lookup = np.array([0] * 26)
        n = len(s1)
        for i in s1: 
            index = ord(i) - ord('a')
            s1_lookup[index] +=1
        #print(s1_lookup)
        L = 0
        for R in range(len(s2)):
            index = ord(s2[R]) - ord('a')          
            s2_lookup[index] += 1
            if R >= n:
                s2_lookup[ord(s2[L]) - ord('a')] -= 1
                L += 1
            #s2_substr = s2[L:R+1]
            #print(L,R,s2_substr,s2_lookup)
            for pos in range(len(s1_lookup)):                
                if s1_lookup[pos] != s2_lookup[pos]:
                    break            
            if pos+1 == len(s1_lookup):
                return True
        return False
原文地址:https://www.cnblogs.com/sandy-t/p/13248825.html