方法一:暴力解法算法
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循環便可解決spa
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算法code