[LeetCode]Permutation in String

题目描述:

LeetCode 567. 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

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,判断s2中是否包含s1的排列。换言之,判断s1的排列是否为s2的子串。

注意:

  1. 给定字符串只包含小写字母
  2. 给定字符串长度范围[1, 10000]

解题思路:

滑动窗口(Sliding Window) 时间复杂度O(n)

由于输入只包含小写字母,因此可以通过统计字母个数判断字符串是否互为对方的排列,其时间复杂度为O(1)。

Python代码:

class Solution(object):
    def checkInclusion(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        l1, l2 = len(s1), len(s2)
        c1 = collections.Counter(s1)
        c2 = collections.Counter()
        p = q = 0
        while q < l2:
            c2[s2[q]] += 1
            if c1 == c2:
                return True
            q += 1
            if q - p + 1 > l1:
                c2[s2[p]] -= 1
                if c2[s2[p]] == 0:
                    del c2[s2[p]]
                p += 1
        return False

滑动窗口算法的改进

在比较s2的窗口部分与s1的字符个数时,跟踪s2的窗口边界发生变化的字符

通过计数器cnt统计s2的窗口部分与s1相等的字符个数

当cnt == len(set(s1))时,返回True

Python代码:

class Solution(object):
    def checkInclusion(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        l1, l2 = len(s1), len(s2)
        c1 = collections.Counter(s1)
        c2 = collections.Counter()
        cnt = 0
        p = q = 0
        while q < l2:
            c2[s2[q]] += 1
            if c1[s2[q]] == c2[s2[q]]:
                cnt += 1
            if cnt == len(c1):
                return True
            q += 1
            if q - p + 1 > l1:
                if c1[s2[p]] == c2[s2[p]]:
                    cnt -= 1
                c2[s2[p]] -= 1
                if c2[s2[p]] == 0:
                    del c2[s2[p]]
                p += 1
        return False

 

本文链接:http://bookshadow.com/weblog/2017/04/30/leetcode-permutation-in-string/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论