Implement strStr()

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

 

posted on 2015-08-30 11:29  horizon.qiang  阅读(87)  评论(0编辑  收藏  举报

导航