1 #pragma once 2 #include "000库函数.h" 3 4 /*********************自解**************/ 5 //使用算法中的find 12ms 6 class Solution { 7 public: 8 int strStr(string haystack, string needle) { 9 if (haystack.size() == 0 && needle.size() != 0)return -1; 10 if (needle.size() == 0)return 0; 11 return haystack.find(needle); 12 } 13 }; 14 15 16 /********************博客解法*****************/ 17 //使用暴力遍寻法 44ms 18 class Solution { 19 public: 20 int strStr(string haystack, string needle) { 21 if (needle.empty()) return 0; 22 int m = haystack.size(), n = needle.size(); 23 if (m < n) return -1; 24 for (int i = 0; i <= m - n; ++i) { 25 int j = 0; 26 for (j = 0; j < n; ++j) { 27 if (haystack[i + j] != needle[j]) break; 28 } 29 if (j == n) return i; 30 } 31 return -1; 32 } 33 }; 34 35 void T028() { 36 string haystack, needle; 37 haystack = "hello"; 38 needle = "ll"; 39 Solution s; 40 cout << s.strStr(haystack, needle) << endl; 41 haystack = "aaaaa"; 42 needle = "bba"; 43 cout << s.strStr(haystack, needle) << endl; 44 }