• 周六. 7 月 27th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

LeetCode题解之 Implement strStr()

admin

11 月 28, 2021

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     }

发表回复