Substring Anagrams

Posted YuriFLAG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Substring Anagrams相关的知识,希望对你有一定的参考价值。

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.

Example

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

思路: HashTable
RelatedProblems : Anagrams Two Strings Are Anagrams

public class Solution {
    /**
     * @param s a string
     * @param p a non-empty string
     * @return a list of index
     */
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        if (s.length() < p.length()) {
            return result;
        }
        int[] numS = new int[256];
        int[] numP = new int[256];
        for (int i = 0; i < p.length(); i++) {
            numS[s.charAt(i) - ‘a‘]++;
            numP[p.charAt(i) - ‘a‘]++;
        }
        if (Arrays.equals(numS,numP)) {
            result.add(0);
        }
        for (int i = p.length(); i < s.length(); i++) {
            numS[s.charAt(i) - ‘a‘]++;
            numS[s.charAt(i - p.length()) - ‘a‘]--;
            if (Arrays.equals(numS,numP)) {
                result.add(i - p.length() + 1);
            }
        }
        return result;
    }
}

 

以上是关于Substring Anagrams的主要内容,如果未能解决你的问题,请参考以下文章

sliding window substring problem汇总贴

精心收集的 48 个 JavaScript 代码片段,仅需 30 秒就可理解

将片段添加到片段中(嵌套片段)

Hackerrank:Sherlock 和 Anagrams [关闭]

slice()和subString()

从 list-codewars 问题中查找单词的 Anagrams