[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
ands2
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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-30uniAPP 实现全屏左右滚动滚动的效果-icode9专业技术文章分享
- 2024-06-30如何在本地使用授权或插件-icode9专业技术文章分享
- 2024-06-30伪静态规则配置方法汇总-icode9专业技术文章分享
- 2024-06-29易优CMS安装常见问题汇总-icode9专业技术文章分享
- 2024-06-28易优新手必读安装教程-icode9专业技术文章分享
- 2024-06-28忘记eyoucms后台密码怎么办?-icode9专业技术文章分享
- 2024-06-26终极指南:Scrum中如何设置需求优先级
- 2024-06-26AI大模型企业应用实战(25)-为Langchain Agent添加记忆功能
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding