abc_begin

导航

28. Implement strStr()【easy】

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 };

 

posted on 2017-09-23 17:43  LastBattle  阅读(134)  评论(0编辑  收藏  举报