栈判断字符串回文

手写栈:

​
#include<iostream>
#include<cstring>
using namespace std;
//搞一个栈结构体 
struct stack{
	int data[1000]; 
	int top;
};
int main()
{
	//定义栈,初始化栈顶 
	stack s;
	s.top=0;
	//定义并初始化需要判断的字符串 
	char str[1000];
	cin>>str;
	//拿到字符串长度,并找到字符串中点 
	int len=strlen(str);
	int mid=len/2-1;
	int i;
	//循环将字符串前把那部分的值全部压入栈中 
	for(i=0;i<=mid;i++)
	{
		s.data[++s.top]=str[i];
	}//因为当字符串为偶数时,mid+1就是后半段字符串,但是为奇数时,mid+2才是后半段字符串 
	if(len%2==1)
	{
		i++;
	}
	//开始循环依次出栈跟后续字符串比较即可 
	while(s.top!=0)
	{
		if(s.data[s.top--]!=str[i++])
		{
			break;
		}
	}
	//如果没有比较到结尾,证明字符串不是回文 
	if(s.top==0)
	{
		cout<<"YES";
	}
	else
	{
		cout<<"NO";
	}
	return 0;
}

​

STL容器:

#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
int main()
{
	stack<int >s;
	char str[1000];
	cin>>str;
	int len=strlen(str);
	int mid=len/2-1;
	int i;
	for(i=0;i<=mid;i++)
	{
		s.push(str[i]);
	}
	if(len%2==1)
	{
		i++;
	}
	while(!s.empty())
	{
		if(s.top()!=str[i++])
		{
			break;
		}
		s.pop();
	}
	if(s.empty())
	{
		cout<<"YES";
	}
	else
	{
		cout<<"NO";
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值