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

更新於 發佈於 閱讀時間約 1 分鐘

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


留言
avatar-img
留言分享你的想法!
avatar-img
Youna's Devlog
7會員
49內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
Youna's Devlog的其他內容
2024/02/13
題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
2024/02/13
題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
2024/01/11
題目 : 100. Same Tree
Thumbnail
2024/01/11
題目 : 100. Same Tree
Thumbnail
2024/01/11
題目 : 83. Remove Duplicates from Sorted List
Thumbnail
2024/01/11
題目 : 83. Remove Duplicates from Sorted List
Thumbnail
看更多
你可能也想看
Thumbnail
「欸!這是在哪裡買的?求連結 🥺」 誰叫你太有品味,一發就讓大家跟著剁手手? 讓你回購再回購的生活好物,是時候該介紹出場了吧! 「開箱你的美好生活」現正召喚各路好物的開箱使者 🤩
Thumbnail
「欸!這是在哪裡買的?求連結 🥺」 誰叫你太有品味,一發就讓大家跟著剁手手? 讓你回購再回購的生活好物,是時候該介紹出場了吧! 「開箱你的美好生活」現正召喚各路好物的開箱使者 🤩
Thumbnail
給定一個字串陣列,請把它們所共有的字元伴隨著出現次數輸出。這篇文章介紹如何使用字典統計出現次數,和字典取交集的方法來解決此問題。並提供了複雜度分析和關鍵知識點。
Thumbnail
給定一個字串陣列,請把它們所共有的字元伴隨著出現次數輸出。這篇文章介紹如何使用字典統計出現次數,和字典取交集的方法來解決此問題。並提供了複雜度分析和關鍵知識點。
Thumbnail
魔鬼藏在二分搜尋裡!輸出值代表的意含、題意產生的邊界條件,寫完模板才是挑戰的開始 Orz
Thumbnail
魔鬼藏在二分搜尋裡!輸出值代表的意含、題意產生的邊界條件,寫完模板才是挑戰的開始 Orz
Thumbnail
題目敘述 題目會給定一個整數陣列arr,要求我們判斷是否每個元素的出現次數都不同? 題目的原文敘述 測試範例 Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurre
Thumbnail
題目敘述 題目會給定一個整數陣列arr,要求我們判斷是否每個元素的出現次數都不同? 題目的原文敘述 測試範例 Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurre
Thumbnail
題目 : 27. Remove Element
Thumbnail
題目 : 27. Remove Element
Thumbnail
題目 : 35. Search Insert Position
Thumbnail
題目 : 35. Search Insert Position
Thumbnail
題目 : 28. Find the Index of the First Occurrence in a String
Thumbnail
題目 : 28. Find the Index of the First Occurrence in a String
Thumbnail
題目:66. Plus One
Thumbnail
題目:66. Plus One
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News