小编Tar*_*nfx的帖子

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

问题很简单在"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++; …
Run Code Online (Sandbox Code Playgroud)

java algorithm

2
推荐指数
1
解决办法
7234
查看次数

标签 统计

algorithm ×1

java ×1