首页 > 代码库 > Implement strStr

Implement strStr

Implement strStr()

 

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

这里用的BF算法实现的,KMP待写...

 1 public class Solution { 2     public int strStr(String haystack, String needle) { 3         boolean found = true; 4         int index = -1; 5         if(0 == haystack.length() && 0 == needle.length()) 6             return 0; 7         if(0 == haystack.length() && 0 == needle.length()) 8             return index; 9         10         for(int i = 0; i <= haystack.length() - needle.length(); i++){11             int k = i;12             found = true;13             for(int j = 0; j < needle.length(); j++){14                 if(haystack.charAt(k) == needle.charAt(j)){15                     k++;16                     continue;17                 }18                 else{19                     j = 0;20                     found = false;21                     break;22                 }23             }//for24             if(found){25                 index = i;26                 break;27             }28         }29         30         return index;31     }32 }

 

Implement strStr