1. 程式人生 > >LeetCode題解之 Implement strStr()

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 }