gpt4 book ai didi

java - 最优化地计算 Haystack 字符串中针字符串的出现次数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:27:01 25 4
gpt4 key购买 nike

问题很简单,不用 String.split("ABC") 在 "ABCDSGDABCSAGAABCCCCAAABAABC"中找到 "ABC"

这是我提出的解决方案,我正在寻找可能比这个更好的解决方案。

public static void main(String[] args) {
String haystack = "ABCDSGDABCSAGAABCCCCAAABAABC";
String needle = "ABC";
char [] needl = needle.toCharArray();
int needleLen = needle.length();
int found=0;
char hay[] = haystack.toCharArray();
int index =0;
int chMatched =0;

for (int i=0; i<hay.length; i++){

if (index >= needleLen || chMatched==0)
index=0;
System.out.print("\nchar-->"+hay[i] + ", with->"+needl[index]);

if(hay[i] == needl[index]){
chMatched++;
System.out.println(", matched");
}else {
chMatched=0;
index=0;
if(hay[i] == needl[index]){
chMatched++;
System.out.print("\nchar->"+hay[i] + ", with->"+needl[index]);
System.out.print(", matched");
}else
continue;
}

if(chMatched == needleLen){
found++;
System.out.println("found. Total ->"+found);
}
index++;
}
System.out.println("Result Found-->"+found);
}

创建这个我花了一段时间。有人可以提出更好的解决方案(如果有的话)附言如果您觉得系统输出很乱,请将其删除。

最佳答案

怎么样:

boolean found = haystack.indexOf("ABC") >= 0;

**编辑 - 该问题询问出现的次数,因此这是上述内容的修改版本:

public static void main(String[] args)
{
String needle = "ABC";
String haystack = "ABCDSGDABCSAGAABCCCCAAABAABC";

int numberOfOccurences = 0;
int index = haystack.indexOf(needle);
while (index != -1)
{
numberOfOccurences++;
haystack = haystack.substring(index+needle.length());
index = haystack.indexOf(needle);
}

System.out.println("" + numberOfOccurences);
}

关于java - 最优化地计算 Haystack 字符串中针字符串的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2515858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com