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

 

相关文章:

  • 2022-01-13
  • 2022-01-16
  • 2021-06-21
  • 2021-08-08
猜你喜欢
  • 2021-06-29
  • 2021-11-15
相关资源
相似解决方案