LeetCode 438. Find All Anagrams in a String--字符串-滑动窗口--C++,Python解法
题目地址:Find All Anagrams in a String - LeetCode
Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"Output:
[0, 6]Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input:
s: "abab" p: "ab"Output:
[0, 1, 2]Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
这道题目的意思很容易懂,就是看s的字母是否是p字符串的排列组合。如果把p字符串的所有可能都列出来,太多了,于是我想到使用counter。
Python解法如下:
from collections import Counter
class Solution:def findAnagrams(self, s: str, p: str) -> List[int]:res = []p_set = dict(Counter(p))lens = len(s)lenp = len(p)if lens < lenp:return resfor i in range(0, lens-lenp+1):s_set = dict(Counter(s[i:i+lenp]))if s_set == p_set:res.append(i)return res
但上面的原始的Python解法会超时,因为有很多重复的工作,使用滑动窗口来减少工作量:
from collections import Counter
class Solution:def findAnagrams(self, s: str, p: str) -> List[int]:res = []p_set = Counter(p)lens = len(s)lenp = len(p)if lens < lenp:return ress_set = Counter(s[0:lenp-1])for i in range(lenp-1, lens):s_set[s[i]] += 1 # include a new char in the windowstart = i-lenp+1if s_set == p_set:res.append(start)s_set[s[start]] -= 1 # decrease the count of oldest char in the windowif s_set[s[start]] == 0:del s_set[s[start]] # remove the count if it is 0return res
上面的解法可以通过了,但可以更快,因为中间还是做了很多无用功,如果能快速跳过不存在的字符,可以更快。
更快的解法:
from collections import Counterclass Solution:def findAnagrams(self, s: str, p: str) -> List[int]:res = []pkey = set(p)p_set = Counter(p)lens = len(s)lenp = len(p)if lens < lenp:return ress_set = Counter(s[0:lenp-1])i = lenp-1while i < lens:if s[i] not in pkey:start = i+1i = start+lenp-1if i >= lens:breaks_set = Counter(s[start:i])continues_set[s[i]] += 1 # include a new char in the windowstart = i-lenp+1if s_set == p_set:res.append(start)# decrease the count of oldest char in the windows_set[s[start]] -= 1if s_set[s[start]] == 0:del s_set[s[start]] # remove the count if it is 0i += 1return res
C++解法如下:
class Solution {public:vector<int> findAnagrams(string s, string p) {vector<int> pv(26,0), sv(26,0), res;if(s.size() < p.size())return res;// fill pv, vector of counters for pattern string and sv, vector of counters for the sliding windowfor(int i = 0; i < p.size(); ++i){++pv[p[i]-'a'];++sv[s[i]-'a'];}if(pv == sv)res.push_back(0);//here window is moving from left to right across the string. //window size is p.size(), so s.size()-p.size() moves are made for(int i = p.size(); i < s.size(); ++i) {// window extends one step to the right. counter for s[i] is incremented ++sv[s[i]-'a'];// since we added one element to the right, // one element to the left should be discarded. //counter for s[i-p.size()] is decremented--sv[s[i-p.size()]-'a']; // if after move to the right the anagram can be composed, // add new position of window's left point to the result if(pv == sv) // this comparison takes O(26), i.e O(1), since both vectors are of fixed size 26. Total complexity O(n)*O(1) = O(n)res.push_back(i-p.size()+1);}return res;}
};
LeetCode 438. Find All Anagrams in a String--字符串-滑动窗口--C++,Python解法相关推荐
- leetcode 438. Find All Anagrams in a String | 438. 找到字符串中所有字母异位词(Java)
题目 https://leetcode.com/problems/find-all-anagrams-in-a-string/ 题解 方法1:尝试构造一种"与顺序无关的哈希" 思考 ...
- leetcode 438. Find All Anagrams in a String 滑动窗口法
题目链接 解析 主要使用滑动窗口法解题,需要好好体会的是中间的两个判断couter的用法,这里很巧妙. 如果想了解更多的滑动窗口法内容,看这里: 滑动窗口法详解 代码 from collections ...
- leetcode Longest Substring with At Most Two Distinct Characters 滑动窗口法
题目解析 代码如下 题目解析 这一题是一道会员的题目,题目介绍如下: Given a string, find the length of the longest substring T that c ...
- LeetCode 159. Longest Substring with At Most Two Distinct Characters --Java,C++,Python解法
题目地址:Longest Substring with At Most Two Distinct Characters - LeetCode Given a string s , find the l ...
- LeetCode 142. Linked List Cycle II--单向链表成环的起点--C++,Python解法
题目地址:Linked List Cycle II - LeetCode Given a linked list, return the node where the cycle begins. If ...
- LeetCode 673. Number of Longest Increasing Subsequence--O(N log N )--Java,C++,Python解法
题目地址:Number of Longest Increasing Subsequence - LeetCode 做这道题目前建议先做:Longest Increasing Subsequence - ...
- LeetCode 2110. 股票平滑下跌阶段的数目(滑动窗口)
文章目录 1. 题目 2. 解题 1. 题目 给你一个整数数组 prices ,表示一支股票的历史每日股价,其中 prices[i] 是这支股票第 i 天的价格. 一个 平滑下降的阶段 定义为:对于 ...
- LeetCode 713. 乘积小于K的子数组(滑动窗口)
1. 题目 给定一个正整数数组 nums. 找出该数组内乘积小于 k 的连续的子数组的个数. 示例 1: 输入: nums = [10,5,2,6], k = 100 输出: 8 解释: 8个乘积小于 ...
- LeetCode 3. 无重复字符的最长子串 (滑动窗口哈希表)
3. 无重复字符的最长子串 题意: 找子串 子串中无重复字符 要求子串长度最长 解法1(暴力法) 思路: 建立一个长度不断变小的滑动窗口 用一个指针指针扫描窗口内的每个元素: 如果除去指针指向的那个元 ...
最新文章
- 报错解决:ad NaCl helper startup ack (0 bytes)
- 计算MySQL的内存峰值公式
- IBM copy service--flashcopy 实验
- Result Maps collection already contains value for ***的问题
- P4197-Peaks【Kruskal重构树,主席树】
- input的type属性的修改
- LeetCode 552. 学生出勤记录 II(动态规划)
- linux字符设备驱动在哪里设置,从点一个灯开始学写Linux字符设备驱动!
- mysql sql执行cmd命令行_命令行执行MySQL的sql文件
- kafka php 安装配置,kafka安装及Kafka-PHP扩展的使用,kafkakafka-php扩展_PHP教程
- MyBatis运行动态sql及存储过程
- 【ACL 2021】基于一致性正则的跨语言微调方法
- java获取文件后缀名(正则表达式)+文件名
- linux 卸载lxde,卸载KDE / Xfce / LXDE 回到纯Unity 的状态
- python抓取网页表格数据
- ​零代码增删改查完全自动化的万能通用接口
- driller fuzz arm问题解决记录
- 您应该购买哪款Apple Watch?
- nRF52832低功耗蓝牙应用开发之入门教程
- 周易Java_关于维度、计算机、周易的漫思
热门文章
- 【问题收录】Eclipse the import java.awt cannot be resolve 问题解决
- Android的ADT的安装(离线)
- java 按钮 事件_Java 添加按钮点击事件
- mysql 转pxc_PXC 配置笔记-从MySQL直接转成PXC集群
- 扩增子和宏基因组数据分析流程和可视化方案—刘永鑫(南京,2020年11月27日)
- 海南大学2020年申请考核博士研究生招生工作办法
- 期刊介绍 | SEL:力争成为土壤生态学界的“Cell”
- 史上最权威宏基因组软件评估—人工重组宏基因组基准数据集
- QIIME 2教程. 03老司机上路指南Experience(2020.11)
- mysql主键始终从小到大_Mysql从入门到入神之(四)B+树索引