Re: [閒聊] 每日LeetCode已回收
28. Find the Index of the First Occurrence in a String
題目 :
給2個字串needle和haystack,
回傳needle第一次出現在haystack中的index,
如果needle不在haystack中則回傳-1
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.
思路 :
for迴圈跑haystack
找到第一個字母符合的就比對一下
=================================
python code :
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
len_needle = len(needle)
for i in range(len(haystack)) :
if haystack[i] == needle[0] :
if i+len_needle-1 < len(haystack) :
if haystack[i:i+len_needle] == needle :
return i
return -1
python直接可以[i:i+長度]比對起來比較方便
其他語言應該不太能這樣寫??
但我看這題related topic有two pointer
不過不太懂要怎麼用two pointer
有大師要解惑嗎??
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.136.203.175 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1677822655.A.041.html
推
03/03 13:57,
2年前
, 1F
03/03 13:57, 1F
→
03/03 13:57,
2年前
, 2F
03/03 13:57, 2F
→
03/03 14:07,
2年前
, 3F
03/03 14:07, 3F
推
03/03 14:10,
2年前
, 4F
03/03 14:10, 4F
→
03/03 14:12,
2年前
, 5F
03/03 14:12, 5F
→
03/03 14:20,
2年前
, 6F
03/03 14:20, 6F
討論串 (同標題文章)
完整討論串 (本文為第 257 之 719 篇):