438. Find All Anagrams in a String
来源:互联网 发布:java分页代码 编辑:程序博客网 时间:2024/05/19 17:55
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".让找所有打乱顺序的substring,返回所有首位置。那么这里参考模板Here is a 10-line template that can solve most 'substring' problems,count初始值应该是需要找的substring的长度,end的判断条件是对应字母的hashmap值 > 0,count--;begin的判断条件是字母的hashmap值 == 0,count++。在while循环里判断一下end - begin == targrtstring.length,如果想等,说明找到的这个substring不包含其他字母,是打乱顺序的target string,记录下现在的begin。代码如下:
public class Solution { public List<Integer> findAnagrams(String s, String p) { List<Integer> list = new ArrayList<Integer>(); int[] map = new int[256]; for (char ch:p.toCharArray()) { map[ch] ++; } int count = p.length(), begin = 0, end = 0; while (end < s.length()) { if (map[s.charAt(end++)]-- > 0) { count --; } while (count == 0) { if (end - begin == p.length()) { list.add(begin); } if (map[s.charAt(begin++)]++ == 0) { count ++; } } } return list; }}
0 0
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String*
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- 438. Find All Anagrams in a String
- LeetCode Find All Anagrams in a String
- leetcode: Find All Anagrams in a String
- leetcode438. Find All Anagrams in a String
- leetcode438. Find All Anagrams in a String
- java.net.MalformedURLException: unknown protocol: classpath
- 灰度共生矩阵的实现
- Android 笔记之横竖屏
- 如何查看某个端口被谁占用
- 四、DC/OS local-universe安装配置
- 438. Find All Anagrams in a String
- UML之类图
- POJ-2387 Til the Cows Come Home(Dijsktra算法求最短路径)
- C语言中有关大小端的介绍(百度笔试题)
- 使用gulp-connect为前端起服务
- ScrollView嵌套使用ListView时遇到,Item显示不全问题
- 刷机包odex的分离与合并
- SQL Server使用本机IP登录不了的解决方法
- 如何计算一个数值的二进制补码?