【字符串】28. 实现 strStr()

题目:

解答:

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) 
 4     {
 5         if(needle == "")
 6         {
 7             return 0;
 8         }
 9         if(haystack == "")
10         {
11             return -1;
12         }
13 
14         int l1 = haystack.size();
15         int l2 = needle.size();
16 
17         for(int i=0; i <= l1 - l2; i++)
18         {
19             int k=i;
20             int j = 0;
21             while(haystack[k] == needle[j] && j<l2 && k<l1)
22             {
23                 k++;
24                 j++;          
25             }
26             if(j == l2)
27             {
28                 return i;
29             }
30         }
31         
32         return -1;
33     }
34 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12822667.html