前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 567. Permutation in String

Leetcode 567. Permutation in String

作者头像
Tyan
发布2021-09-06 15:40:47
3230
发布2021-09-06 15:40:47
举报
文章被收录于专栏:SnailTyanSnailTyan

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

Permutation in String
Permutation in String

2. Solution

**解析:**Version 1,此题与leetcode 438非常类似,思路是一样的。判断s2是否包含s1的变换,可以采用字典的方法,即每个字母的个数及类型相等。先统计字符串s1的字母个数并记录其长度在stat中,遍历字符串s2,如果字母在stat中,则将其记录到字典subs中,否则重置subs,当subs['length'] = stat['length']时,比较二者是否相等,如果相等,直接返回True,否则,字符串继续遍历,为保证subs长度与stat长度一致,此时,subs中移除s2[index - n + 1]字符,同时长度减1

  • Version 1
代码语言:javascript
复制
class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        n = len(s1)
        stat = collections.Counter(s1)
        stat['length'] = n
        subs = collections.defaultdict(int)
        for index, ch in enumerate(s2):
            if ch in stat:
                subs[ch] += 1
                subs['length'] += 1
            else:
                subs = collections.defaultdict(int)
                continue
            if subs['length'] == stat['length']:
                if stat == subs:
                    return True
                subs[s2[index - n + 1]] -= 1
                subs['length'] -= 1
        return False

Reference

  1. https://leetcode.com/problems/permutation-in-string/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-08-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档