1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| // 实现strStr.cpp: 定义控制台应用程序的入口点。 //
#include "stdafx.h" #include <iostream> #include <string> using namespace std;
class Solution { public: int strStr(string haystack, string needle) { int len1 = haystack.length(); int len2 = needle.length(); int j = 0; if (len2 == 0) return 0; if (len2 > len1) return -1; for (int i = 0; i < len1; i++) { if (haystack[i] == needle[0]) { int m = i; for (j = 0; j < len2; j++) { if (haystack[m] == needle[j]) { m++; } else break; } if (j == len2)return i; } } return -1; } };
int main() { string s1 = "haystack", s2 = "sta"; Solution s; int len = s.strStr(s1, s2); cout << len << endl; return 0; }
|