# 子串第一次出现位置

利用for else。KMP？

```python
class Solution:
    def strStr(self, source, target):
        if source is None or target is None:
            return -1

        for i in range(len(source) - len(target) + 1):  # 从到第一个位置，到倒数第子串长位置遍历
            for j in range(len(target)):  # 遍历一遍子串
                if source[i + j] != target[j]:  # 只要i开头的串，有一个和子串不一样，就退出开始下一个起点
                    break
            else:  # python 魔法，当上面的for全部正常运行完时，执行else，也就是全部匹配子串不break
                return i
        return -1


s = Solution()
a = s.strStr('acdbcdbdse', 'dbd')
print(a)


#5
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/sou-suo-cha-zhao-lei/zi-chuang-wei-zhi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
