码迷,mamicode.com
首页 > 其他好文 > 详细

Substring Anagrams

时间:2017-07-15 22:43:37      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:substring   att   empty   lower   bst   solution   class   div   param   

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

标签:substring   att   empty   lower   bst   solution   class   div   param   

原文地址:http://www.cnblogs.com/FLAGyuri/p/7186014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!