首页 > 其他 > 详细

Implement strStr()

时间:2015-04-19 16:07:54      阅读:274      评论:0      收藏:0      [点我收藏+]

Implement strStr().

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

 

Analyse: Pay special attention to when the length of haystack is less  than that of needle, and the case that needle is empty.

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

Implement strStr()

原文:http://www.cnblogs.com/amazingzoe/p/4439241.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!