首页 > 代码库 > Find All Anagrams in a String Leetcode

Find All Anagrams in a String Leetcode

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

 

这道题有个很巧妙的移动窗口法,count表示当前left开始的第二个stirng长度的字符串中,有几个不是存在于第二个string里面的,初始值为第二个string的长度。这道题需要回顾一下。

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res = new ArrayList<>();
        if (s == null || p == null || s.length() == 0 || p.length() == 0) {
            return res;
        }
        int[] hash = new int[26];
        for (int i = 0; i < p.length(); i++) {
            hash[p.charAt(i) - ‘a‘]++;
        }
        int left = 0, right = 0, count = p.length();
        while (right < s.length()) {
            if (hash[s.charAt(right) - ‘a‘] >= 1) {
                count--;
            }
            hash[s.charAt(right) - ‘a‘]--;
            right++;
            
            if (count == 0) {
                res.add(left);
            }
            
            if (right - left == p.length()) {
                if (hash[s.charAt(left) - ‘a‘] >= 0) {
                    count++;
                }
                hash[s.charAt(left) - ‘a‘]++;
                left++;
            }
        }
        return res;
    }
    
}

还有一个问题就是

hash[s.charAt(left) - ‘a‘]++;

这句话为什么不能写在if的里面,到时候再来考虑一下。。。现在还不是很能理解。。。

Find All Anagrams in a String Leetcode