> For the complete documentation index, see [llms.txt](https://longxingtan.gitbook.io/mle-interview/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://longxingtan.gitbook.io/mle-interview/01_leetcode/04_string/28.-find-the-index-of-the-first-occurrence-in-a-string.md).

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

<https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/>

## solution

* kmp匹配

```python
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        for i in range(len(haystack)):
            if haystack[i] == needle[0]:
                j = i
                k = 0
                while j < len(haystack) and k < len(needle) and haystack[j] == needle[k]:
                    j += 1
                    k += 1
                if k == len(needle):
                    return i
        return -1
```

时间复杂度：O()\
空间复杂度：O()
