实现 strStr()
描述:🤔
错误代码
c语言代码⬇️
void get_next(char* ch, int* next){
int i = 0,j = -1;
next[0] = -1;
while(i < strlen(ch) - 1){
if(j == -1 || ch[i] == ch[j]){
++i; ++j;
next[i] = j;
}else{
j = next[j];
}
}
}
int Index_KMP(char * haystack, char * needle, int * next){
int i = 0, j = 0;
while(i < strlen(haystack) && j < strlen(needle)){
if(j == -1 || haystack[i] == needle[j]){
++i; ++j;
}else{
j = next[j];
}
}
if(j >= strlen(needle)){
return i - strlen(needle);
}
return -1;
}
int strStr(char * haystack, char * needle){
int len = strlen(needle);
int* next = (int*)malloc(sizeof(int) * len);
get_next(needle, next);
return Index_KMP(haystack, needle, next);
}
错误原因:我不知道,在vs里面答案是正确的,在力扣里就错了,相同时空,相同代码,得出的结果不同,说明什么,说明物理学不存在了,bro。
现在知道了,thanks god,科学还在,it was my fault.
在vs中正确,是因为我没有引入string.h头文件,导致vs默认将strlen的返回值设置为int,最终导致我的结果正确,实际返回值是size_t,是无符号整数。
通过代码
通过代码1⬇️
void get_next(char* ch, int* next){
int i = 0,j = -1;
next[0] = -1;
while(i < strlen(ch) - 1){
if(j == -1 || ch[i] == ch[j]){
++i; ++j;
next[i] = j;
}else{
j = next[j];
}
}
}
int Index_KMP(char * haystack, char * needle, int * next){
int i = 0, j = 0;
int len1 = strlen(haystack);
int len2 = strlen(needle);
while(i < len1 && j < len2){
//return 32; 进了while循环
if(j == -1 || haystack[i] == needle[j]){
//return 11;//为什么没进if 把strlen(needle)先返回给int型再用作判断就进入if了
++i; ++j;
}else{
j = next[j];
//return j; j == -1;
}
}
if(j >= strlen(needle)){
return i - strlen(needle);
//return i;
}
return -1;
}
int strStr(char * haystack, char * needle){
int len = strlen(needle);
int* next = (int*)malloc(sizeof(int) * len);
get_next(needle, next);
return Index_KMP(haystack, needle, next);
//return strlen(needle);
//return next[0];
}
通过代码2⬇️
总结
总结:
Q1:strlen返回值怎么看是有符号,还是无符号
A: size_t
这是无符号整数类型,它是 sizeof 关键字的结果。
Q2:无符号数和有符号数作比较的规则
A:无符号数和有符号数运算,看成无符号数,返回的也是无符号数
假如 int a = -1 和 unsigned int b = 1 作比较
在8位的机子上,a的二进制原码表示为1000 0001,补码为1111 1110,b的机器码为0000 0001
Q3:无符号数和有符号数作比较时的底层逻辑,是靠减法来实现的吗
A:是