Implement strStr()

Implement strStr().

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

 

Analyse: Pay special attention to when the length of haystack is less  than that of needle, and the case that needle is empty.

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle){
 4         int index = -1;
 5         if(haystack.length() < needle.length()) return index;
 6         else if(needle.length() == 0) return 0;
 7         
 8         for(int j = 0; j <= haystack.length() - needle.length(); j++){
 9             int index_needle = 0;
10             if(haystack[j] == needle[index_needle]){
11                 index = j;
12                 for(int k = 1; k < needle.length(); k++){
13                     if(haystack[j+k] != needle[index_needle+k]){
14                         index = -1;
15                         break;
16                     }
17                 }
18             }
19             if(index >= 0) return index;
20         }
21         return index;
22     }
23 };

你可能感兴趣的:(imp)