287. Find the Position of a Substring within a String

You are given two strings:

  • text: the main string
  • pattern: the substring to search for

Return the index of the first occurrence of pattern in text. If pattern is not found, return -1.

Example 1:

Input: text = "takeuforward", pattern = "forward"

Output: 5

Explanation: The substring "forward" begins at index 5 in "takeuforward"

Example 2:

Input: text = "hello", pattern = "az"

Output: -1

Explanation: "az" does not occur in "hello"

Now Your Turn!

Pick the correct output for the given input

Input: text = "aaaaaaa", pattern = "aaa"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= text.length, pattern.length <= 105
  • Strings consist of lowercase and uppercase English letters
  • The search should be case-sensitive
0
class Solution {
public:
int findSubstring(const string& text, const string& pattern) {
// Your code goes here
}
};
Test Case

Input:

Pattern
Text