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

Implement strStr()

时间:2015-08-30 12:36:58      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

Implement strStr().

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

 

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4        //这个题不难,关键是条件有很多,要判断对
 5        //a   0    0
 6        //0   0    0
 7        //0   a    -1
 8        //haystack长度    needle长度    返回值
 9        //如果needle比haystack长,返回-1
10         if(needle.size() == 0)
11             return 0;
12             
13         if(haystack.size() == 0 && needle.size() != 0)
14             return -1;
15     
16         if(haystack.size() < needle.size())
17             return -1;
18             
19         for(int i = 0; i < haystack.size() - needle.size() + 1; i++){
20             
21             int j = 0;
22             for(j; j < needle.size(); j++){
23                 if(haystack[i+j] != needle[j])
24                     break;
25             }
26             if(j == needle.size())
27                 return i;
28         }
29         return -1;
30         
31     }
32 };

 

Implement strStr()

标签:

原文地址:http://www.cnblogs.com/horizonice/p/4770549.html

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