Skip to main content

28. Find the Index of the First Occurrence in a String

Hint

class Solution {
public:
int strStr(string haystack, string needle)
{
// Iterate through 'haystack' from the start to the point where 'needle' can fit
for ()
{
// Iterate through each character in 'needle'
for ()
{
// If the characters don't match, break out of the inner loop

// If we reach the end of 'needle' and all characters have matched
if ()
{
// Return the starting index of the first occurrence of 'needle' in 'haystack'
}
}
}
// If 'needle' is not found in 'haystack', return -1
}
};
class Solution {
public:
int strStr(string haystack, string needle)
{
for (int i = 0; i <= haystack.size() - needle.size(); ++i)
{
for (int j = 0; j < needle.size(); ++j)
{
if (needle[j] != haystack[i + j]) break;
if (j == needle.size() - 1)
{
return i;
}
}
}
return -1;
}
};
  • T: O(nm)O(n * m)
  • S: O(1)O(1)