Java implementation LeetCode 438 ectopic find all the letters in the word string

438. ectopic find all the letters in the word string

Given a string s and a non-empty string starting index p, find all s is a substring of ectopic word letter p, and returns the substring.

String contains only lowercase letters, and the character string length p and s is not more than 20,100.

Description:

Ectopic word letters refer to the same letters, but arranged in different strings.
The order of the answers that were not considered.
Example 1:

Input:
S: "cbaebabacd" P: "ABC"

Output:
[0, 6]

Explanation:
The starting index of 0 is equal to the substring "cba", which is "abc" ectopic letter words.
6 substring starting index is equal to "bac", which is "abc" ectopic letter words.
Example 2:

Input:
S: "ABAB" P: "ab &"

Output:
[0, 1, 2]

Explanation:
The starting index of 0 is equal to the substring "ab", which is "ab" ectopic letter words.
Substring starting index 1 is equal to "ba", which is "ab" ectopic letter words.
2 substring starting index is equal to "ab", which is "ab" ectopic letter words.

class Solution {
 
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res = new ArrayList<>();
        if (p.length() > s.length())
            return res;

        int[] pLetterCounts = new int[26];
        int[] sLetterCounts = new int[26];
        for (int i = 0; i < p.length(); ++i) {
            pLetterCounts[p.charAt(i) - 'a']++;
            sLetterCounts[s.charAt(i) - 'a']++;
        }

        for (int endIdx = p.length() - 1; endIdx < s.length(); ++endIdx) {
            int startIdx = endIdx - p.length() + 1;
            boolean isAnagrams = true;
            for (int i = 0; i < 26; ++i) {
                if (sLetterCounts[i] != pLetterCounts[i]) {
                    isAnagrams = false;
                    break;
                }
            }

            if (isAnagrams)
                res.add(startIdx);

            if (endIdx != s.length() - 1){
                sLetterCounts[s.charAt(startIdx) - 'a']--;
                sLetterCounts[s.charAt(endIdx + 1) - 'a']++;
            }

        }

        return res;
    }
}
Released 1545 original articles · won praise 20000 + · views 2.19 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104910582