http://blog.csdn.net/runningtortoises/article/details/45667569
题目大意:
给两个字符串,求第二个字符串在第一个字符串中出现的最小位置,如果没有出现则输出-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<len1 && j<len2){
- if(j==-1 || chs1[i]==chs2[j]){
- i++;j++;
- }else{
- j=next[j];
- }
- }
- if(j<len2)return -1;
- return i-len2;
- }
- private void getNext(char[] chs,int[] next,int len){
- int i=0,j=-1;
- next[0]=-1;
- while(i<len){
- if(j==-1 || chs[i]==chs[j]){
- i++;j++;
- next[i]=j;
- }else{
- j=next[j];
- }
- }
- }
- }
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<len1 && j<len2){
- if(j==-1 || haystack[i]==needle[j]){
- i++;j++;
- }else{
- j=next[j];
- }
- }
- if(j<len2)return -1;
- else return i-len2;
- }
- private:
- void getNext(string needle,int* next,int len1){
- int i=0,j=-1;
- next[0]=-1;
- while(i<len1){
- if(j==-1 || needle[i]==needle[j]){
- j++;i++;
- next[i]=j;
- }else{
- j=next[j];
- }
- }
- }
- };
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<len1 and j<len2:
- if j==-1 or haystack[i]==needle[j]:
- i+=1;j+=1
- else:j=next[j]
- if j<len2:return -1
- else:return i-len2
- def getNext(self,needle,next,len2):
- i=0;j=-1
- while i<len2:
- if j==-1 or needle[i]==needle[j]:
- i+=1
- j+=1
- next[i]=j
- else:j=next[j]
Java Solution 1 - Naive
Java Solution 2 - KMP
Check out this article to understand KMP algorithm.
http://blog.csdn.net/zz198808/article/details/7883588