[LeetCode]Find All Anagrams in a String

Find All Anagrams in a String
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.code

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

1.解題思路string

anagrams,就是隻順序不一樣但個數相同的字符串,那咱們就能夠利用hashtable的思想來比較每一個字符串中字符出現的個數是否相等。
對於兩個字符串咱們分別準備數組(大小爲256)來存儲每一個字符出現的次數:
1) 對於p,咱們遍歷,並在hp中記錄字符出現的次數;
2) 以後遍歷s,先把當前字符的個數+1,可是須要考慮當前index是否已經超過了p的長度,若是超過,則表示前面的字符已經不予考慮,因此要將index-plen的字符的個數-1;最後判斷兩個數組是否相等,若是相等,返回index-plen+1,即爲開始的下標。hash

2.代碼it

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res=new ArrayList<Integer>();
        if(s.length()==0||s==null||p.length()==0||p==null) return res;
        int[] hs=new int[256];
        int[] hp=new int[256];
        int plen=p.length();
        for(int i=0;i<plen;i++){
            hp[p.charAt(i)]++;
        }
        for(int j=0;j<s.length();j++){
            hs[s.charAt(j)]++;
            if(j>=plen){
                hs[s.charAt(j-plen)]--;
            }
            if(Arrays.equals(hs,hp))
                res.add(j-plen+1);
        }
        return res;
    }
}
相關文章
相關標籤/搜索