438. Find All Anagrams in a String 查找字符串中的所有Anagrams
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".
p都找完后,添加到结果中即可:
if (end - start == t.length()) {
results.add(start);
}
class Solution { public List<Integer> findAnagrams(String s, String t) { //定义map HashMap<Character, Integer> map = new HashMap<>(); List<Integer> results = new LinkedList<>(); int start = 0, end = 0; //cc if (s.length() < t.length()) return results; //定义counter for (char c : t.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } int count = map.size(); //while循环 //end的减少 while (end < s.length()) { char charAtEnd = s.charAt(end); if (map.containsKey(charAtEnd)) { map.put(charAtEnd, map.get(charAtEnd) - 1); if (map.get(charAtEnd) == 0) count--; } end++; while (count == 0) { char charAtStart = s.charAt(start); if (map.containsKey(charAtStart)) { map.put(charAtStart, map.get(charAtStart) + 1); if (map.get(charAtStart) > 0) count++; } //更新head if (end - start == t.length()) { results.add(start); } //start往前移 start++; } } //返回 return results; } }