我对我为练习编写的这段代码有疑问。我必须检查字符串是否是回文。我无法更改函数的声明。当所有字母都相同(如“aaaa”)时,该函数仅返回 1 ,但如果我用其他回文(如“anna”)对句子进行充电,该函数将返回 0 ,我不明白为什么会出现这种情况。谢谢!
char* cargar (char*);
int pali (char*);
int main()
{
char*texto=NULL;
texto=cargar(texto);
int res=pali(texto);
if(res==1){printf("\nPalindrome");}
else printf("\nNot palindrome");
return 0;
}
char* cargar (char*texto)
{
char letra;
int i=0;
texto=malloc(sizeof(char));
letra=getche();
*(texto+i)=letra;
while(letra!='\r'){
i++;
texto=realloc(texto,(i+1)*sizeof(char));
letra=getche();
*(texto+i)=letra;}
*(texto+i)='\0';
return texto;
}
int pali (char* texto)
{
int i;
for(i=0;*(texto+i)!='\0';i++){
}i--;
if(i==0||i==1){return 1;}
if(*texto==*(texto+i)){
return pali(++texto);
}
else return 0;
}
最佳答案
您确定字符串是否为回文的函数没有经过深思熟虑。
假设您有一个长度为 l
的字符串 s
。字符串中的字符布局如下:
Indices: 0 1 2 3 l-4 l-3 l-2 l-1
+----+----+----+----+- ... -+----+----+----+----+
| | | | | ... | | | | |
+----+----+----+----+- ... -+----+----+----+----+
如果字符串是回文,
s[0] = s[l-1]
s[1] = s[l-2]
...
当 LHS 的索引大于或等于 RHS 索引。
要将其转换为代码,
int is_palindrome(char const* s)
{
size_t len = strlen(s);
if ( len == 0 ) // An empty string a palindrome
{
return 1;
}
size_t i = 0;
size_t j = len-1;
for ( ; i < j; ++i, --j )
{
if ( s[i] != s[j] )
{
// the string is not a palindrome.
return 0;
}
}
// If we don't return from inside the for loop,
// the string is a palindrome.
return 1;
}
关于C 中检查字符串是否为回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31397373/