计算Haystack字符串中针头串的出现,最佳?

Tar*_*nfx 2 java algorithm

问题很简单在"ABCDSGDABCSAGAABCCCCAAABAABC"中查找"ABC"而不使用String.split("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);
 }
Run Code Online (Sandbox Code Playgroud)

我花了一段时间创造这个.有人可以建议一个更好的解决方案(如果有的话)PS如果它们看起来很麻烦,就丢弃它们.

Chr*_*ght 5

怎么样:

boolean found = haystack.indexOf("ABC") >= 0;
Run Code Online (Sandbox Code Playgroud)

**编辑 - 问题询问出现的次数,所以这里是上面的修改版本:

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);
}
Run Code Online (Sandbox Code Playgroud)