LeetCode #438: Find All Anagrams in a String
来源:互联网 发布:收银机软件免费 编辑:程序博客网 时间:2024/05/29 18:48
Problem Statement
(Source) 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".
Solution
A “Sliding Window” like algorithm.
class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ from collections import Counter res = [] n1, n2 = len(s), len(p) cnt1, cnt2 = Counter(s[:n2]), Counter(p) for index in xrange(n1 - n2 + 1): if cnt1 == cnt2: res.append(index) if index == n1 - n2: break cnt1[s[index]] -= 1 cnt1[s[index + n2]] += 1 if cnt1[s[index]] == 0: cnt1.pop(s[index]) return res
[To be optimised]
0 0
- LeetCode Find All Anagrams in a String
- leetcode: Find All Anagrams in a String
- [LeetCode]Find All Anagrams in a String
- Leetcode Find All Anagrams in a String
- LeetCode : Find All Anagrams in a String
- leetcode[Find All Anagrams in a String]
- LeetCode #438: Find All Anagrams in a String
- LeetCode 438: Find All Anagrams in a String
- Leetcode 438 Find All Anagrams in a String
- [python]leetcode(438). Find All Anagrams in a String
- LeetCode 438 Find All Anagrams in a String
- LeetCode 438 Find All Anagrams in a String解析
- 438 Find All Anagrams in a String
- leetcode 438. Find All Anagrams in a String
- LeetCode 438. Find All Anagrams in a String
- LeetCode 438. Find All Anagrams in a String
- [leetcode] 438. Find All Anagrams in a String 解题报告
- 【leetcode】438. Find All Anagrams in a String【E】
- 第九周项目3(2)----矩阵相加
- EasyUI之对话框Dialog
- java 间断执行多条命令ssh连接,有缺陷
- 【软件项目管理】任务(活动)之间的排序依据主要有:强制性依赖关系、软逻辑关系、外部依赖关系
- R tutorial 16 - Multiple Regression 回归分析 (1)
- LeetCode #438: Find All Anagrams in a String
- echart动态图表
- Shell 脚本简介
- C/C++经典程序训练3---模拟计算器
- spring 发送邮件
- javascript数据结构与算法-简单算法
- 安装TensorFlow(Ubuntu+CUDA+Cudnn)
- 设计并实现一个大规模分布式BOTNET系统(一)
- C语言实验——某年某月的天数