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".
思路: HashTableRelatedProblems : 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; } }
时间: 2024-10-01 05:02:51