palindrome

Algorithm 专栏收录该内容
24 篇文章 0 订阅

A string that reads the same thing as the inverse reads (excluding whitespace) is called palindrome. 

Such as string: "Madam im Adam", "Dad" are palindrome.

Design algorithm to determine whether a string is palindrome,

 requires the use of stack to achieve discrimination of palindrome.

#include <iostream>
#include <cstring>
using namespace std;
#define MaxSize 1000
class SqStack
{
	public:
		SqStack();
		bool isEmpty();
		void push(char ch);
		char pop();
		void Print();
		void Palindrome();
	private:
		char data[MaxSize];
		int top;
};
SqStack::SqStack()
{
	this->top=-1;
}
bool SqStack::isEmpty()
{
	if(this->top=-1)
		return true;
	else
		return false;	
}
void SqStack::push(char ch)
{
	if(top == MaxSize-1)
		cout<<"栈满"<<endl;
	else
	{
		++top;
		data[top] = ch;
	}
}
char SqStack::pop()	
{
	char ch;
	if(top==-1)
	{
		cout<<"栈空"<<endl;
		return 0;
	}
	else
	{
		ch = data[top];
		--top;
	}
	return ch;
}
void SqStack::Palindrome()
{
	bool tag = true;
	int n = top;
	for(int i =0;i<(top+1)/2;++i)
	{
		if(data[i]!=data[n])
		{
			tag = false;
			break;
		}
		n--;
	}
	if(tag)
		cout<<"回文数"<<endl;
	else 
		cout<<"非回文数"<<endl;
}
void SqStack::Print()	
{
	if(top==-1)
		cout<<"栈空"<<endl;
	else
		cout<<data<<endl;
}
int main()
{
	SqStack sq1,sq2;
	string s;
	cin>>s;
	char q;
	cout<<"字符串长度:"<<s.length()<<endl;
	for(int i= 0;i<s.length()/2;++i)
	{
		sq1.push(s[i]);
		sq2.push(s[s.length()-1-i]);
	}
	cout<<"字符串为:"<<s<<endl; 
	int tag=true;
	for(int i= 0;i<s.length()/2;++i)
	{
		if(sq1.pop()!=sq2.pop())
		{
			tag = false;
			break;
		}
	}
	if(tag)
		cout<<s<<"是回文数"<<endl;
	else
		cout<<s<<"不是回文数"<<endl;
	//sq.Palindrome();
	//sq.pop(q);//出栈 

	return 0;
}


  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值