首页 > 其他 > 详细

28. Implement strStr()【easy】

时间:2017-09-23 19:42:23      阅读:217      评论:0      收藏:0      [点我收藏+]

28. Implement strStr()【easy】

Implement strStr().

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

 

解法一:

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

 

28. Implement strStr()【easy】

原文:http://www.cnblogs.com/abc-begin/p/7581897.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!