码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 28. Implement strStr()

时间:2016-06-24 23:44:39      阅读:492      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/implement-strstr/

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

  • 字符串简单题。一定要写的没BUG。
  • 如果不在函数最后一行写return语句的话,LeetCode会出RUNTIME ERROR。
Line 27: control reaches end of non-void function [-Werror=return-type]
  • strstr - C++ Reference
    •   http://www.cplusplus.com/reference/cstring/strstr/?kw=strstr 
 
技术分享
 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     int strStr(string haystack, string needle) 
 8     {
 9         // Corner case
10         if (needle.empty()) return 0;
11         if (haystack.empty()) return -1;
12         
13         int n = haystack.length() - needle.length() + 1;
14 
15         // better use < rather than <=
16         for (int i = 0; i < n; i ++)
17         {
18               bool flag = true;
19               
20               for (int j = 0; j < needle.length(); j ++)
21               {
22                   if (haystack.at(i + j) != needle.at(j))
23                   {
24                     flag = false;
25                     break;
26                   }
27               }
28               
29               if (flag) 
30                  return i;
31         }
32         
33         return -1;
34     }    
35 };
36 
37 int main ()
38 {
39     Solution testSolution;
40     string s1 = "mississippi";
41     string s2 = "issi";
42     
43     cout << testSolution.strStr(s1, s2) << endl;
44     
45     getchar();
46     
47     return 0;
48 }
View Code

 

LeetCode 28. Implement strStr()

标签:

原文地址:http://www.cnblogs.com/pegasus923/p/5615555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!