0
点赞
收藏
分享

微信扫一扫

【Leetcode 28】 实现strStr()

【Leetcode 28】 实现strStr()_python

方法1:

【Leetcode 28】 实现strStr()_java_02

python版本

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
c=-1
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)]==needle:
c=i
break
return c

java版本

class Solution {
public int strStr(String haystack, String needle) {
int L = needle.length(), n = haystack.length();

for (int start = 0; start < n - L + 1; ++start) {
if (haystack.substring(start, start + L).equals(needle)) {
return start;
}
}
return -1;
}
}

注意时间复杂度,总共得比较次数是N-L+1次,这里把常数级给忽略掉了
【Leetcode 28】 实现strStr()_java_03

方法2:使用KMP算法
​​​ https://leetcode-cn.com/problems/implement-strstr/solution/kmp-suan-fa-xiang-jie-by-labuladong/​​

题目参考链接
​​​ https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode/​​


举报

相关推荐

0 条评论