更新於 2024/06/18閱讀時間約 1 分鐘

[Leetcode] 28. Find the Index of the First Occurrence in ...

題目 : 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:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.


1.

這一題可以直接使用python中的find()方法

s.find(str)可以檢測字串中是否有包含指定的字串(str)

有包含 : 回傳指定的字串(str)第一個字元在字串(s)中的索引值

沒有包含 : 回傳False

class Solution:
def strStr(self, haystack: str, needle: str) -> int:

return haystack.find(needle)


分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.