description
Achieve strStr () function.
Given a string and a needle haystack string, a position of the needle to find the first occurrence of the string (starting from 0) in the haystack string. If not, it returns -1.
Examples of
ideas
answer
- python
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
len1=len(haystack)
len2=len(needle)
# i+len2-1=len1-1---i==len1-len2--i<len1-len2+1
for i in range(len1-len2+1):
if haystack[i:i+len2]==needle:
return i
return -1
- c++
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.size(),len2=needle.size();
// i+len2-1=len1-1---i==len1-len2--i<len1-len2+1
for (int i=0; i<len1-len2+1; i++)
if (haystack.substr(i,len2)==needle)
return i;
return -1;
}
};