方法一:暴力解法
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] = '