namespace Palindrome
{
class Program
{
public static bool IsPalindrome(string s)
{
int min = 0;
int max = s.Length - 1;
while (true)
{
if (min > max) // True if we've compared up to, and then gone passed the middle of the string.
return true;
if (char.ToLower(s[min++]) != char.ToLower(s[max]))
return false;
}
}
static void Main(string[] args)
{
string [] words = {
"civic",
"deified",
// ...
"stats",
"tenet",
};
foreach (string value in words)
{
Console.WriteLine("{0} = {1}", value, IsPalindrome(value));
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey(true); }
}
}该程序检查单词数组中的单词是否为回文(向前拼写与向后拼写相同的单词)。
Main中的foreach循环将数组中的每个单词传递给IsPalindrome()函数;该函数测试单词,并相应地返回True或False。
因为当前数组中的每个单词都是一个回文,所以当程序运行时,它应该输出所有当前单词,后跟True。然而,它给了我错误的答案。为什么会这样呢?
发布于 2014-12-11 19:38:25
在我看来,您似乎忘记了减少max的值;即:
if (char.ToLower(s[min++]) != char.ToLower(s[max]))..。应该是:
if (char.ToLower(s[min++]) != char.ToLower(s[max--]))无论如何,如果您在调试模式下运行它,并逐步执行您的代码,那么您应该能够很快地将其清除。
发布于 2014-12-11 19:38:00
试一试
if (char.ToLower(s[min++]) != char.ToLower(s[max--]))
return false;发布于 2014-12-11 19:37:50
我想你忘了递减你的max变量。
现在,您只需将每个字母与最后一个字母进行比较。
https://stackoverflow.com/questions/27421885
复制相似问题