Re: [闲聊] 每日LeetCode

楼主: umi0912umi (UMI)   2023-03-03 13:50:53
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
有大师要解惑吗??
作者: idiont (supertroller)   2023-03-03 13:57:00
Rabin-Karp algorithm吗 我是懒得自己写字串比对 直接string.find()看一下讨论区说的two-pointer都是O(nm)的做法 没有O(n+m)
作者: NTHUlagka (拉卡)   2023-03-03 14:10:00
这题要O(m+n)就KMP吧 O(m*n)蛮接近不会过的边缘了
楼主: umi0912umi (UMI)   2023-03-03 14:12:00
没听过KMP 研究一下那是啥 我好烂QQ
作者: idiont (supertroller)   2023-03-03 14:20:00
kmp z-value 还有上面那个 都是线性的字串比对算法

Links booklink

Contact Us: admin [ a t ] ucptt.com