ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[leetcode] 567. Permutation in String

2022-02-27 02:00:19  阅读:160  来源: 互联网

标签:map return String s2 s1 start Permutation now leetcode


题目

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

标签:map,return,String,s2,s1,start,Permutation,now,leetcode
来源: https://www.cnblogs.com/frankming/p/15941367.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有