码迷,mamicode.com
首页 > 其他好文 > 详细

LeeCode28 Implement strStr()

时间:2016-08-16 21:59:00      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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 };

 

LeeCode28 Implement strStr()

标签:

原文地址:http://www.cnblogs.com/wangxiaobao/p/5777923.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!