- 实现 strStr()
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = “hello”, needle = “ll”
输出:2
示例 2:
输入:haystack = “aaaaa”, needle = “bba”
输出:-1
示例 3:
输入:haystack = “”, needle = “”
输出:0
相关文章:
Java中String的indexof()的用法
Java代码:
class Solution {
public int strStr(String haystack, String needle) {
int index=haystack.indexOf(needle);
return index;
}
}
C代码:
// i 指向后缀末尾
// j 指向前缀末尾,还代表i之前最长相等前后缀的长度-1,因为下标从1开始,next是多加了一的
//在下标为1的时候,next数组的意思是匹配失败j移动的位置,也等于失败位置前面最长公共前后缀加1
int * Getnext(char *s)
{
int len = strlen(s);
char *s1 = (char*)malloc(sizeof(char) *(len+2));//拷贝一下字符串,变为下标从1开始存储
for(int q=0;q<len;q++)
{
s1[q+1] = s[q];
}
s1[len+1] = '\0';
int *next = (int*)malloc(sizeof(int) *(len+1));//多分配一个空间,下面是++j,++i,不然会下标越界
int j=0,i=1;
next[1] = 0;
while(i<len)
{
if(j==0||s1[i]==s1[j])
{
next[++i] = ++j;//next[2]必为1
}
else
{
j = next[j];//找next数组就是模式串前后缀自匹配,如果失败就回溯
}
}
return next;
}
int strStr(char * haystack, char * needle)
{
int len1 = strlen(haystack);
int len2 = strlen(needle);
if(len2 == 0) return 0;
//因为下标从1开始,所以得复制一下,默认从0开始...
char* haystack1 = (char *)malloc(sizeof(char)*(len1+2));
char* needle1 = (char *)malloc(sizeof(char)*(len2+2));
int q=0;
for(q=0;q<len1;q++)
{
haystack1[q+1] = haystack[q];
}
haystack1[len1+1] = '\0';
for(q=0;q<len2;q++)
{
needle1[q+1] = needle[q];
}
needle1[len2+1] = '\0';
int *next = Getnext(needle);//拿到next数组
int j=1 ,i=1;
while(i<=len1&&j<=len2)
{
if(j==0||haystack1[i]==needle1[j])
{
++i;
++j;
if(j>len2)
{
return i-len2-1;
}
}
else{
j = next[j];
}
}
return -1;
}
python3代码:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
def get_max_len(sub_str):
max_len, str_len = 0, len(sub_str)
for i in range(str_len-1):
if sub_str[:i+1] == sub_str[str_len-i-1:]:
max_len = i + 1 if i + 1 > max_len else max_len
return max_len
m, n = len(haystack), len(needle)
if not needle or not haystack:
return 0
## KMP algorithm
prefix = []
for i in range(n):
prefix.append(get_max_len(needle[:i+1]))
prefix.insert(0, 0)
i, j = 0, 0
while i < n:
if j >= m:
return -1
if haystack[j] != needle[i]:
if i:
j -= 1
i = prefix[i]
else:
i += 1
j += 1
return j - i