28. Implement strStr () [implemented strstr ()]

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
Here Insert Picture Description
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;
    }
};
Published 78 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/puspos/article/details/103152500