[leetcode] 567. Permutation in String

2022/2/27 6:22:53

本文主要是介绍[leetcode] 567. Permutation in String,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目

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

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

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:

  • 1 <= s1.length, s2.length <= 10^4
  • s1 and s2 consist of lowercase English letters.

思路

使用字典保存s1中所有字符的数量,使用滑动窗口遍历s2,使用字典保存窗口中的值,当s1字典和s2字典相同时,则返回true,否则在遍历结束后返回false。

代码

python版本:

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        s1_map = {}
        s2_map = {}
        for i in s1:
            if i in s1_map:
                s1_map[i] += 1
            else:
                s1_map[i] = 1
        start = 0
        for now in s2:
            if now in s1_map and (now not in s2_map or s2_map[now] < s1_map[now]):
                if now not in s2_map:
                    s2_map[now] = 1
                else:
                    s2_map[now] += 1
                equal = True
                for k, v in s1_map.items():
                    if k not in s2_map or s2_map[k] != v:
                        equal = False
                        break
                if equal:
                    return True
            else:
                while s2[start] != now:
                    if s2[start] in s2_map:
                        s2_map[s2[start]] -= 1
                    start += 1
                start += 1
        return False



这篇关于[leetcode] 567. Permutation in String的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程