【LeeCode 2017/07/01】28. Implement strStr()
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 };
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 };
posted on 2017-07-01 14:04 Wurq 閱讀(113) 評論(0) 編輯 收藏 引用 所屬分類: 【LeeCode 每日N題】
