Leetcode Day 尋找字串中第一次出現的索引解釋

王林
發布: 2024-07-18 14:51:47
原創
528 人瀏覽過

Leetcode Day Find the Index of the First Occurrence in a String Explained

問題如下:

給定兩個字串needle和haystack,傳回needle在haystack中第一次出現的索引,如果needle不是haystack的一部分,則傳回-1。

範例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.
登入後複製

範例2:

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

我是這樣解決的:

這是第一個簡單的問題,其實很簡單。只需使用內建的 index() 函數即可!
這是它的工作原理:

  • 檢查「needle」是否是「haystack」的子字串
  • 如果是,則傳回第一次出現 'needle' 的索引
  • 否則如果沒有找到“needle”,則回傳-1
if needle in haystack:
    return haystack.index(needle)
else:
    return -1
登入後複製

這是完整的解決方案:

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.index(needle) if needle in haystack else -1
登入後複製

以上是Leetcode Day 尋找字串中第一次出現的索引解釋的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!