可能你可以告诉我道路,我至少可以开始。我只能使用C语言。任务有非常具体的限制,我不能以任何方式打破它们。任务是:
strlen()
。int palindrom(char* str);
我开始写作,但不再有任何想法了:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int palindrom(char* str)
{
int len = strlen(str);
if (str[0] != str[len - 1]) return 0;
}
int main(void)
{
char string1[] = "ROTATOR";
char string2[] = "8536358";
char string3[] = "Palindrome";
if (palindrom(string1)) printf("%s is Palindrome\n", string1);
else printf("%s is not Palindrome\n", string1);
if (palindrom(string2)) printf("%s is Palindrome\n", string2);
else printf("%s is not Palindrome\n", string2);
if (palindrom(string3)) printf("%s is Palindrome\n", string3);
else printf("%s is not Palindrome\n", string3);
return 0;
}
答案 0 :(得分:1)
这样的东西会起作用吗?
Something like this will work ?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
bool palindrom_helper(char* str, int first, int last)
{
if(first >= last)
return true;
if (str[first] != str[last])
return false;
return (palindrom(str, first+1, last-1));
}
bool palindrom(char* str)
{
return palindrom_helper(str, 0, strlen(str)-1);
}
int main(void)
{
char string1[] = "ROTATOR";
char string2[] = "8536358";
char string3[] = "Palindrome";
if (palindrom(string1)) printf("%s is Palindrome\n", string1);
else printf("%s is not Palindrome\n", string1);
if (palindrom(string2)) printf("%s is Palindrome\n", string2);
else printf("%s is not Palindrome\n", string2);
if (palindrom(string3)) printf("%s is Palindrome\n", string3);
else printf("%s is not Palindrome\n", string3);
return 0;
}
你应该只使用strlen函数一次。所以你不能在递归调用的函数中使用它。
我在这里做的是先初始化,然后最后为0和len-1然后递归(第一个+ 1,最后一个-1)。
如果函数找到一对不匹配的字母,它将返回false。否则它会继续直到它们一起到达中心(奇数长度的字符串)或彼此交叉(甚至是长度字符串)然后返回true(因为那意味着他们没有在他们的路径上看到任何不匹配的字母)
另外,我不明白你在递归函数中的单个转换是什么意思吗?
答案 1 :(得分:1)
如何解决的线索在于限制:可以更改字符串,但只有在函数结束时才会返回。通过打印结果来检查该条件。
#include <stdio.h>
#include <string.h>
int palindrom(char* str)
{
size_t len = strlen(str);
int res;
if(len < 2) {
return 1; // cannot shorten: must be success
}
if(str[0] != str[len - 1]) { // make palindrome test
return 0;
}
str[len - 1] = '\0'; // shorten the string at the back
res = palindrom(str + 1); // recurse woth string shortened at the front
str[len - 1] = str[0]; // replace last char (we know it's the same)
return res;
}
int main(void)
{
char string1[] = "ROTATOR";
char string2[] = "8536358";
char string3[] = "Palindrome";
char string4[] = "A";
char *wrd[] = { "not ", "" };
printf("%s is %sa Palindrome\n", string1, wrd[ palindrom(string1) ]);
printf("%s is %sa Palindrome\n", string2, wrd[ palindrom(string2) ]);
printf("%s is %sa Palindrome\n", string3, wrd[ palindrom(string3) ]);
printf("%s is %sa Palindrome\n", string4, wrd[ palindrom(string4) ]);
return 0;
}
节目输出:
ROTATOR is a Palindrome
8536358 is a Palindrome
Palindrome is not a Palindrome
A is a Palindrome