Find the Index of the First Occurrence in a String
LeetCode #28 · Easy · Strings · C++ solution with worked-out approach and complexity analysis.
Approach
Use built-in string find function
The find() function returns the position of the first occurrence, or string::npos if not found.
Time
O(n*m)
worst case
Space
O(1)
Problem description(from LeetCode)
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Examples
Example 1
- Input:
- haystack = "sadbutsad", needle = "sad"
- Output:
- 0
Constraints
- •1 <= haystack.length, needle.length <= 10^4
- •haystack and needle consist of only lowercase English characters.
C++ Solution
solution.cpp
class Solution {
public:
int strStr(string haystack, string needle) {
auto ind = haystack.find(needle);
return ind != string::npos ? int(ind) : -1;
}
};