首页 > 代码库 > leetcode------Implement strStr()

leetcode------Implement strStr()

标题:Implement strStr()
通过率:21.8%
难度:简单

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

本题意思就是字符串匹配,返回匹配到的开头位置,那么我首先想到了KMP算法,但是KMP算法我已经完全忘记了,于是我想先写个暴力解法就是从头开始匹配,不相同的话到下个位置开始匹配。

惊人的是我写完代码并且通过以后我去看那个solution,上面竟然说暴力解法是最优的解法,面试的时候直接用暴力解法就行了,并且字符串越长暴力解法的优势越明显,那么具体代码如下:

 1 public class Solution { 2     public int strStr(String haystack, String needle) { 3         int stacklen=haystack.length(); 4         int needlelen=needle.length(); 5         int j=0; 6         if(needlelen==0&&stacklen==0)return 0; 7         if(needlelen==0&&stacklen!=0) return 0; 8         if(needlelen>stacklen) return -1; 9         for(int i=0;i<=stacklen-needlelen;i++){10             int tmp=i;11             for(j=0;j<needlelen;j++){12                 if(needle.charAt(j)!=haystack.charAt(tmp)) break;13                 tmp++;14             }15             if(j==needlelen) return i;16         }17         return -1;18     }19 }

 下面我把solution的贴出来:

O(nm) runtime, O(1) space – Brute force:You could demonstrate to your interviewer that this problem can be solved using known efficient algorithms such as Rabin-Karp algorithm, KMP algorithm, and the Boyer- Moore algorithm. Since these algorithms are usually studied in an advanced algorithms class, it is sufficient to solve it using the most direct method in an interview – The brute force method.The brute force method is straightforward to implement. We scan the needle with the haystack from its first position and start matching all subsequent letters one by one. If one of the letters does not match, we start over again with the next position in the haystack.The key is to implement the solution cleanly without dealing with each edge case separately.

 

leetcode------Implement strStr()