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

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

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

題目 : 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
Youna's Devlog
7會員
49內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言
avatar-img
留言分享你的想法!
Youna's Devlog 的其他內容
題目:66. Plus One
題目 : 9. Palindrome Number
題目 : 14. Longest Common Prefix
題目 : 13. Roman to Integer
128. Longest Consecutive Sequence 解題
題目:66. Plus One
題目 : 9. Palindrome Number
題目 : 14. Longest Common Prefix
題目 : 13. Roman to Integer
128. Longest Consecutive Sequence 解題