实现strStr()函数

方法一:暴力解法

 1 int strStr(string haystack, string needle) {
 2     if (needle.empty())
 3         return 0;
 4 
 5     int M = haystack.size();
 6     int N = needle.size();
 7 
 8     for (int i = 0; i <= M - N; i++)
 9     {
10         int j;
11         for (j = 0; j < N; j++)
12         {
13             if (needle[j] != haystack[i + j])
14             {
15                 break;
16             }
17         }
18         if (j == N)
19             return i;
20     }
21     return -1;
22 }

方法二:利用memcmp,一层for循环即可解决

 1 int strStr(string haystack, string needle) {
 2     if (needle.empty())
 3         return 0;
 4 
 5     int M = haystack.size();
 6     int N = needle.size();
 7 
 8     char* m = new char[M + 1];
 9     char* n = new char[N + 1];
10 
11     memcpy(m, haystack.c_str(), M);
12     memcpy(n, needle.c_str(),    N);
13     m[M] = '\0';
14     n[N] = '\0';
15 
16     for (int i = 0; i <= M - N; i++)
17     {
18         if (0 == memcmp(&m[i], n, N))
19         {
20             delete[] m;
21             delete[] n;
22             return i;
23         }
24     }
25 
26     delete[] m;
27     delete[] n;
28 
29     return -1;
30 }

方法三: KMP算法

posted @ 2019-10-10 20:16  朴者  阅读(1657)  评论(0编辑  收藏  举报