题目
描述:https://leetcode.cn/leetbook/read/array-and-string/conm7/
错误代码
c语言代码⬇️
char * longestPalindrome(char * s){
int i = 0;
int j = 0;
int size = 0;
char *ret = (char *)malloc(sizeof(char)*1000);
int lo;
int hi;
while(s[j] != '\0'){
i = j;
while(i > 0 && s[i+2] != '\0'){
int k = 1;
int oddSize = 1;
while(i - k > 0 && s[i+k] != '\0'){
if(s[i-k] == s[i+k]){
oddSize += 2;
}
k++;
}
if(oddSize > size){
size = oddSize;
lo = i - k + 1;
hi = i + k - 1;
}
i++;
}
i = j;
while(i >=0 && s[i+2] != '\0'){
int k = 1;
int evenSize = 0;
while(i - k > 0 && s[i+k] != '\0'){
if(s[i-k+1] == s[i+k]){
evenSize += 2;
}
k++;
}
if(evenSize > size){
size = evenSize;
lo = i - k + 1;
hi = i + k - 1;
}
i++;
}
j++;
}
i = 0;
for(int l = lo; l <= hi; l++){
ret[i++] = s[l];
}
ret[i] = '\0';
return ret;
}
错误原因:数组又越界了,bro
假设数组s只有一个元素,第十行的0+2,要访问s[2],直接越界。
错误代码2↓
char * longestPalindrome(char * s){
int i = 0;
int j = 0;
int size = 0;
int strLen = strlen(s);
char *ret = (char *)malloc(sizeof(char)*10000);
int lo;
int hi;
while(s[j] != '\0'){
i = j;
while(i >= 0 && i < strLen){
int k = 1;
int oddSize = 1;
while(i - k >= 0 && i + k < strLen){
if(s[i-k] == s[i+k]){
oddSize += 2;
}else{
break;
}
k++;
}
if(oddSize > size){
size = oddSize;
lo = i - k + 1;
hi = i + k - 1;
}
i++;
}
i = j;
while(i >=0 && i < strLen - 1){
int k = 1;
int evenSize = 0;
while(i - k + 1 >= 0 && i + k < strLen){
if(s[i-k+1] == s[i+k]){
evenSize += 2;
}else{
break;
}
k++;
}
if(evenSize > size){
size = evenSize;
lo = i - k + 2;
hi = i + k - 1;
}
i++;
}
j++;
}
i = 0;
for(int l = lo; l <= hi; l++){
ret[i++] = s[l];
}
ret[i] = '\0';
return ret;
}
超时了,这真是,太fucking crazy了
通过代码
通过代码1⬇️
char * longestPalindrome(char * s){
int i,j;
int start = 0;
int maxLen = 1;
int strLen = strlen(s);
if(strLen <= 1){//如果等于1,应该也对
return s;
}
int lo;
int hi;
i = 0;
while(s[i] != '\0'){
//回文串为奇数个元素
lo = i - 1;
hi = i + 1;
while(lo >= 0 && hi < strLen && s[lo] == s[hi]){
lo--;
hi++;
}
if(hi - lo - 1 > maxLen){
maxLen = hi - lo - 1;
start = lo + 1;
}
//回文串为偶数个元素
lo = i;
hi = i + 1;
while(lo >= 0 && hi < strLen && s[lo] == s[hi]){
lo--;
hi++;
}
if(hi - lo - 1 > maxLen){
maxLen = hi - lo - 1;
start = lo + 1;
}
i++;
}
char *ret = (char *)malloc(sizeof(char)*(maxLen+1));
i = 0;
for( ; i < maxLen; i++){
ret[i] = s[start++];
}
ret[i] = '\0';
return ret;
}
通过代码2⬇️
总结
总结:指定是8行了,你拿我当牲口了?