https://leetcode.cn/problems/find-all-anagrams-in-a-string/
给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。
示例 1:
输入: s = "cbaebabacd", p = "abc" 输出: [0,6] 解释: 起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。 起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。
示例 2:
输入: s = "abab", p = "ab" 输出: [0,1,2] 解释: 起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。 起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。 起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。
提示:
1 <= s.length, p.length <= 3 * 104s和p仅包含小写字母
public class hot438 {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
if (s.length() < p.length()){
return res;
}
int[] pCount = new int[26];
for (char c : p.toCharArray()){
pCount[c - 'a']++;
}
int windowLen = p.length();
//读取第一个窗口
int[] windowCount = new int[26];
for (int i = 0; i < windowLen; i++) {
windowCount[s.charAt(i) - 'a']++;
}
if (Arrays.equals(pCount, windowCount)){
res.add(0);
}
for (int i = windowLen; i < s.length(); i++){
windowCount[s.charAt(i) - 'a']++;
windowCount[s.charAt(i - windowLen) - 'a']--;
if (Arrays.equals(pCount, windowCount)){
res.add(i - windowLen + 1);
}
}
return res;
}
}
1万+

被折叠的 条评论
为什么被折叠?



