28. Implement strStr() (C++)

Implement strStr().

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

solution:

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         if(needle.length()==0) return 0;
 5         int len=haystack.length()-needle.length();
 6         for(int i=0;i<len+1;i++){
 7             int j=0;
 8             for(;j<needle.length();j++){
 9                 if(haystack[i+j]!=needle[j]){
10                     break;
11                 }
12             }
13             if(j==needle.length()){
14                 return i;
15             }
16         }
17         return -1;
18     }
19 };
原文地址:https://www.cnblogs.com/devin-guwz/p/6519523.html