438.Find All Anagrams in a String
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".
class Solution {
public static List findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
if (s == null || s.length() == 0 || p == null || p.length() == 0)
return result;
int[] hash = new int[256];
char[] pp = p.toCharArray();
for (char i : pp)
hash[i]++; //例如i是a,则数组对应的hash[97]上的数字变化,直接把字符变成ascii码
int left = 0;
int right = 0;
int count = p.length();
while (right < s.length()) {
if (hash[s.charAt(right)] > 0) {
count--;
}
hash[s.charAt(right)]--;
right++; //窗口右移;相应的hash值减小;如果这个位置的Hash值是正的,表示p字符串也包含这个,所以count做减法
if (count == 0)
result.add(left);//count指示器,为0表示和p对应的hash值完全一致
if (right - left == p.length() ) {
if (hash[s.charAt(left)] >= 0) {
count++;
}
hash[s.charAt(left)]++;
left++;
//如果当窗口大小一定的时候即窗口大小和需要比较的字符串大小一致的时候,将窗口左边 的指针向右边移动,
//移动的同时左边的字符计数因为在第一个if的地方hash值减小过,
//所以需要执行对应恢复操作,即:hash值增加,count计数值增加。
}
}
return result;
}
}
分类:
String
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix