Substring Anagrams

来源:互联网 发布:粒子群算法缺点 编辑:程序博客网 时间:2024/06/07 07:50

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 40,000.

The order of output does not matter.

样例

Given s = "cbaebabacd" p = "abc"

return [0, 6]

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".



public List<Integer> findAnagrams(String s, String p) {        int[] mapP = new int[200];        //记录p中字母出现的次数        List<Integer> lists = new ArrayList<>();        for (int i = 0; i < p.length(); i++) {            mapP[p.charAt(i)]++;        }        int left = 0, windowSize = p.length();        for (int right = 0; right < s.length(); right++) {            //如果当前字符在p中出现,则将map出现次数减一,并将窗口大小减一表示已经匹配一个            if (--mapP[s.charAt(right)] >= 0) windowSize--;            //当窗口长度与p的长度相等,表示已经检查过从left到right位置的串            if ((right - left + 1) == p.length()) {                if (windowSize == 0) {                    //全部匹配,记录左边坐标                    lists.add(left);                }                //最左边第一个字符在p中的次数恢复一,窗口向右移一格                if (++mapP[s.charAt(left++)] >= 1)                    //待匹配数加一                    windowSize++;            }        }        return lists;    }


原创粉丝点击