LeetCode题解之 Implement strStr()

1、题目描述

2.题目分析

字符串操作,注意边界条件即可。

3.代码

 1  int strStr(string haystack, string needle) {
 2         int n = needle.size();
 3         int res = -1;
 4         if( needle.size() == 0)
 5             return 0;
 6         for(string::iterator it = haystack.begin() ; it != haystack.end(); ++it){
 7             if((*it) == needle[0]){
 8                 bool isEqual = true;
 9                 bool isEnd = false;
10                 for(int i = 0 ; i < n; i++){
11                     if( it + i == haystack.end() ){
12                         isEnd = true;
13                         break;
14                     }
15                     if( needle[i] != *(it+i)){
16                         isEqual = false;
17                         break;
18                     }
19                 }
20                 if( isEnd == true )
21                     break;
22                 if( isEqual == true){
23                     res = it-haystack.begin();
24                     break;
25                 }
26                 
27             }
28         }
29         return res;
30         
31     }

 

posted @ 2018-11-12 11:05  山里的小勇子  阅读(175)  评论(0编辑  收藏  举报