-
Notifications
You must be signed in to change notification settings - Fork 0
【Day 83 】2023-08-31 - 28 实现 strStr( #85
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
|
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
if not haystack or len(haystack) < len(needle):
return -1
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return -1 |
思路暴力法时间复杂度m*n,滚动哈希选的好,直接是m+n 代码#暴力法和滚动哈希
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not haystack and not needle:
return 0
if not haystack or len(haystack)<len(needle):
return -1
if not needle:
return 0
hash_val=0
tar=0
prime=101
for i in range(len(haystack)):
if i<len(needle):
hash_val=hash_val*26+(ord(haystack[i])-ord("a"))
hash_val%=prime
tar=tar*26+(ord(needle[i])-ord("a"))
tar%=prime
else:
hash_val = (hash_val - (ord(haystack[i - len(needle)]) - ord("a")) * ((26 ** (len(needle) - 1)) % prime)) * 26 + (ord(haystack[i]) - ord("a"))#更新哈希表的值,减去左边,加上右边
hash_val%=prime
if i>=len(needle)-1 and hash_val==tar and haystack[i-len(needle)+1:i+1]==needle:
return i-len(needle)+1
return 0 if hash_val==tar and haystack[i-len(needle)+1:i+1]==needle else -1
复杂度分析
|
代码class Solution {
public int strStr(String ss, String pp) {
int n = ss.length(), m = pp.length();
char[] s = ss.toCharArray(), p = pp.toCharArray();
// 枚举原串的「发起点」
for (int i = 0; i <= n - m; i++) {
// 从原串的「发起点」和匹配串的「首位」开始,尝试匹配
int a = i, b = 0;
while (b < m && s[a] == p[b]) {
a++;
b++;
}
// 如果能够完全匹配,返回原串的「发起点」下标
if (b == m) return i;
}
return -1;
}
} |
class Solution { |
代码class Solution:
def strStr(self, s: str, t: str) -> int:
def prefix_function(s):
n = len(s)
pi = [0] * n
j = 0
for i in range(1, n):
while j>0 and s[i] != s[j]:
j = pi[j-1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
n, m = len(s), len(t)
pi = prefix_function(t)
j = 0
for i in range(n):
while j>0 and s[i] != t[j]:
j = pi[j-1]
if s[i] == t[j]:
j += 1
if j == m:
return i-m+1
return -1 |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
28 实现 strStr(
入选理由
暂无
题目地址
[ 之 BF&RK 篇)
https://leetcode-cn.com/problems/implement-strstr/]( 之 BF&RK 篇)
https://leetcode-cn.com/problems/implement-strstr/)
前置知识
题目描述
The text was updated successfully, but these errors were encountered: