Leetcode 0028. Find the Index of the First Occurrence in a String
28. Find the Index of the First Occurrence in a String
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.
Example 1:
1 | Input: haystack = "sadbutsad", needle = "sad" |
Example 2:
1 | Input: haystack = "leetcode", needle = "leeto" |
题目大意
给定两个字符串 haystack 和 needle,返回 needle 在 haystack 中第一次出现的位置。如果 needle 不是 haystack 的一部分,则返回 -1。
解题思路
可以使用滑动窗口的思想来解决这个问题:
- 遍历
haystack,从每个可能的起始位置开始 - 检查以当前位置为起点,长度为
needle长度的子串是否与needle匹配 - 如果找到匹配的子串,返回当前起始位置
- 如果遍历结束仍未找到匹配,返回 -1
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.

