LeetCode28 Implement strStr()

题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. (Easy)

分析:

不用考虑KMP啥的,就是写好暴力写法就行。

两重循环,注意空串判定,注意haystack比needle长,注意外层循环的终止条件。

代码:

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         if (haystack.size() == 0 && needle.size() == 0) {
 5             return 0;
 6         }
 7         if (haystack.size() < needle.size()) {
 8             return -1;
 9         }
10         for (int i = 0; i < haystack.size() - needle.size() + 1; ++i) {
11             int flag = 1;
12             for (int j = 0; j < needle.size(); ++j) {
13                 if (haystack[i + j] != needle[j]) {
14                     flag = 0;
15                     break;
16                 }
17             }
18             if (flag == 1) {
19                 return i;
20             }
21         }
22         return -1;
23     }
24 };

 

posted @ 2016-08-16 21:18  wangxiaobao1114  阅读(184)  评论(0编辑  收藏  举报