这是用于在字符串中查找Anagram的代码。我如何进一步优化它给我带来错误
LeetCode Q:
很好。但是,这给了我一个错误的错误。为了运行此程序,我必须做什么更改?
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int[] fors=new int[26];
int[] forp=new int[26];
for(int i=0;i<p.length();i++){
forp[p.charAt(i)-'a']++;
}
int k=p.length();
int len=s.length();
int i=0;
int j=0;
ArrayList<Integer> list=new ArrayList<>();
if(s.length()<p.length()) return list;
while(j<len){
fors[s.charAt(j)-'a']++;
if(j-i+1<k)j++;
if(j-i+1==k){
if(areSame(fors,forp)){
list.add(j-k+1);
fors[s.charAt(i)-'a']--;
i++;
j++;
}
}
}
return list;
}
public boolean areSame(int[] countS, int[] countP){
for(int i=0;i<26;i++){
if(countS[i]!=countP[i]){
return false;
}
}
return true;
}
}
LeetCode Q:https://leetcode.com/problems/find-all-anagrams-in-a-string/
I believe what I have done is perfectly fine. However, it's giving me a TLE error. What changes do I have to do in order to run this program?
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int[] fors=new int[26];
int[] forp=new int[26];
for(int i=0;i<p.length();i++){
forp[p.charAt(i)-'a']++;
}
int k=p.length();
int len=s.length();
int i=0;
int j=0;
ArrayList<Integer> list=new ArrayList<>();
if(s.length()<p.length()) return list;
while(j<len){
fors[s.charAt(j)-'a']++;
if(j-i+1<k)j++;
if(j-i+1==k){
if(areSame(fors,forp)){
list.add(j-k+1);
fors[s.charAt(i)-'a']--;
i++;
j++;
}
}
}
return list;
}
public boolean areSame(int[] countS, int[] countP){
for(int i=0;i<26;i++){
if(countS[i]!=countP[i]){
return false;
}
}
return true;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我看到您的代码有2个问题。首先,关于TLE,您有一个无限的循环,因为您要迭代J,并且我只有在窗户相等的情况下。
你应该迭代我,无论如何。解决此问题就像将迭代从if情况外移出一样简单。
请注意,我也将S-计数器移出,以便您即使Aresame Checker为False,也可以继续移动。
第二个问题是您如何迭代j。通过在Aresame检查之前递增J,您可以过早检查Windows 1的大小。您可以通过将j迭代移至末尾来解决此问题:)
I see 2 issues with your code. First, regarding TLE, you have an infinite loop because you iterate j and i only if the windows are equal.
You should iterate i regardless. Fixing this is as simple as moving the iteration out of the if case.
Notice that I also move out the S - counter so that you keep moving even if the areSame checker is false.
The second issue is how you iterate j. By incrementing j before the areSame check, you check the windows 1 size too early. You can fix this by moving the j iteration to the end :)