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