第1个回答 2013-10-12
class ReplyWord
{
/// <summary>
/// 判断是否回文
/// </summary>
/// <param name="item">所要判断的字符串</param>
/// <returns>是就返回true,否就返回false</returns>
public static bool IsReplyWord(string item)
{
if (item.Length == 0) return false;
IStack<string> WordStack = new LinkStack<string>();//新建一个对象栈,用来存储所要判断的字符
IQueue<string> WordQueue = new LinkQueue<string>();//新建一个对象队列,也是用来存储所要判断的字符
//将字符串入栈,和入队
for (int i = 0; i < item.Length; i++)
{
WordStack.Push(item.Substring(i, 1));//将字符逐个入栈
WordQueue.In(item.Substring(i, 1));//将字符逐个入队
}
while (!WordStack.IsEmpty && !WordQueue.IsEmpty)
{
//栈是后进先出,队列是先进先出
//刚好将出栈元素与出队元素相比较,不相等则不是回文
if (WordStack.Pop() != WordQueue.Out())
{
return false;//发现不相等则返回false
}
}
return true;//经过比较后没有发现不相等,则是回文,返回true
}
}
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("检测回文演示:\n------------------------------------------------------");
Console.WriteLine("请输入你要检测的字符(-1退出):");
string input = Console.ReadLine();
if (input == "-1") return;
if (ReplyWord.IsReplyWord(input))
{
Console.WriteLine("你的所输入的字符'{0}'是回文!", input);
}
else
{
Console.WriteLine("不好意思,你的所输入的字符'{0}'不是回文!", input);
}
Console.WriteLine("按任意键继续...");
Console.ReadKey();
Console.Clear();
}
}
}