-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_the_index_of_the_first_occurrence_in_a_string.cpp
More file actions
67 lines (51 loc) · 1.84 KB
/
find_the_index_of_the_first_occurrence_in_a_string.cpp
File metadata and controls
67 lines (51 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
28. Find the Index of the First Occurrence in a String
Time Complexity: O(n * m)
Space Complexity: O(1)
where n = len(haystack), m = len(needle)
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) {
return 0;
}
int n = haystack.length();
int m = needle.length();
for (int i = 0; i <= n - m; i++) {
if (haystack.substr(i, m) == needle) {
return i;
}
}
return -1;
}
int strStrBuiltIn(string haystack, string needle) {
size_t pos = haystack.find(needle);
return (pos != string::npos) ? pos : -1;
}
};
// Test cases
int main() {
Solution solution;
// Example 1
cout << "Example 1: " << solution.strStr("sadbutsad", "sad") << endl; // Expected: 0
// Example 2
cout << "Example 2: " << solution.strStr("leetcode", "leeto") << endl; // Expected: -1
// Edge case: needle at end
cout << "Example 3: " << solution.strStr("hello", "llo") << endl; // Expected: 2
// Edge case: needle is entire haystack
cout << "Example 4: " << solution.strStr("test", "test") << endl; // Expected: 0
// Edge case: single character
cout << "Example 5: " << solution.strStr("a", "a") << endl; // Expected: 0
// Edge case: needle longer than haystack
cout << "Example 6: " << solution.strStr("ab", "abc") << endl; // Expected: -1
// Edge case: multiple occurrences
cout << "Example 7: " << solution.strStr("ababcaababcaabc", "ababcaabc") << endl; // Expected: 6
// Test built-in method
cout << "Example 8 (built-in): " << solution.strStrBuiltIn("sadbutsad", "sad") << endl; // Expected: 0
return 0;
}