[LeetCode28] Implement strStr()

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

in Java, there is an API function name indexof(), it returns index within this string of the first occurrence of the specified substring. 

java 实现

[java] view plain copy
  1. public String strStr(String haystack, String needle) {  
  2.         if(haystack.length()<=0return null;  
  3.         int i = haystack.indexOf(needle);  
  4.         if(i==-1return null;  
  5.         else{  
  6.             return haystack.substring(i);  
  7.         }  
  8.     }  

another solution:

[java] view plain copy
  1. public String strStr(String haystack, String needle) {  
  2.         if(haystack.length()<=0 && needle.length()>0return null;  
  3.         for(int i=0;i<=haystack.length()-needle.length();i++){  
  4.             boolean flag = true;  
  5.             for(int j=0;j<needle.length();j++){  
  6.                 if(haystack.charAt(i+j)!=needle.charAt(j)){  
  7.                     flag = false;  
  8.                     break;  
  9.                 }  
  10.             }  
  11.             if(flag){  
  12.                 return haystack.substring(i);  
  13.             }  
  14.         }  
  15.         return null;  
  16.     }  

Below two solutions is overkill for interview.

third solution: rolling hash

http://blog.csdn.net/yanghua_kobe/article/details/8914970

fourth solution: KMP

http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html


For c++

strightforward use point scan from begin to end, but this complexity is O(M*N)

[cpp] view plain copy
  1. char *strStr(char *haystack, char *needle) {  
  2.       if(!haystack || !needle) return NULL;  
  3.     int hlength = strlen(haystack);  
  4.     int nlength = strlen(needle);  
  5.     if(hlength<nlength) return NULL;  
  6.     for(int i=0; i<hlength-nlength+1;i++){  
  7.         char *p = &haystack[i];  
  8.         int j=0;  
  9.         for(;j<nlength;j++){  
  10.             if(*p == needle[j])  
  11.                 p++;  
  12.             else  
  13.                 break;  
  14.         }  
  15.         if(j == nlength)  
  16.             return &haystack[i];  
  17.     }  
  18.     return NULL;  
  19.     }  


the best solution is KMP, complexity is O(N)

你可能感兴趣的:(LeetCode)