LeetCode 28 Implement strStr() (C,C++,Java,Python)

Problem: 【LeetCode 28 Implement strStr() (C,C++,Java,Python)】 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 buttonto reset your code definition.
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.
经典的KMP应用,暴力什么的还是不要提了,参考这里: 从头到尾彻底理解KMP

题目大意: 给两个字符串,求第二个字符串在第一个字符串中出现的最小位置,如果没有出现则输出-1

Java源代码(323ms):

public class Solution { public int strStr(String haystack, String needle) { char[] chs1=haystack.toCharArray(); char[] chs2=needle.toCharArray(); int len1=chs1.length,len2=chs2.length; int[] next=new int[len2+1]; getNext(chs2,next,len2); int i=0,j=0; while(i



C语言源代码(2ms):
void getNext(char *needle,int* next){ int i=0,j=-1; next[0]=-1; while(needle[i]){ if(j==-1 || needle[j]==needle[i]){ j++; i++; next[i]=j; }else{ j=next[j]; } } } int strStr(char* haystack, char* needle) { int length=strlen(needle),i=0,j=0; int *next=(int*)malloc(sizeof(int)*(length+1)); getNext(needle,next); while(j==-1 || (haystack[i] && needle[j])){ if(j==-1 || haystack[i]==needle[j]){ j++; i++; }else{ j=next[j]; } } if(needle[j])return -1; else return i-length; }


C++源代码(8ms):
class Solution { public: int strStr(string haystack, string needle) { int len1=haystack.size(),len2=needle.size(); int* next=(int*)malloc(sizeof(int)*(len2+1)); getNext(needle,next,len2); int i=0,j=0; while(i


Python源代码(74ms):
class Solution: # @param {string} haystack # @param {string} needle # @return {integer} def strStr(self, haystack, needle): len1=len(haystack); len2=len(needle) next=[-1 for i in range(len2+1)] self.getNext(needle,next,len2) i=0; j=0 while i



    推荐阅读