1 // 子串为空则任意匹配
2 class Solution {
3 public:
4 int strStr(string haystack, string needle) {
5 int len_s = haystack.length();
6 int len_t = needle.length();
7
8 bool is_cmp = (haystack == needle) || needle == "";
9 for (int i = 0; i < len_s; i++)
10 {
11 if (haystack[i] != needle[0])
12 continue;
13
14 is_cmp = true;
15 for (int j = 0; j < len_t; j++) {
16 if (i + j<len_s && haystack[i + j] == needle[j])
17 continue;
18
19 is_cmp = false;
20 break;
21 }
22
23 if (is_cmp)
24 return i;
25 }
26
27 return is_cmp ? 0 : -1;
28 }
29 };