【问题描述】
所谓回文字符串就是指正读反读均相同的字符序列。
如“123a321”和“aba”均是回文,但“abc”不是回文。
通过栈这个数据结构我们将很容易判断一个字符串是否为回文。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
int main() {
int next;
string a,s;
cin>>a;
int len=a.size(); //length of a string
int mid=len/2-1; //midpoint of a string
int top=-1; //Initialization of the stack
for(int i=0; i<=mid; i++) s[++top]=a[i]; //push
//find the starting subscript to match
if(len%2==0) next=mid+1;
else next=mid+2;
for(int i=next; i<=len-1; i++) { //match
if(a[i]!=s[top]) break;
top--;
}
if(top==-1) cout<<"YES";
else cout<<"NO";
return 0;
}
/*
in:
123a321
out:
YES
*/
【参考文献】
https://www.ituring.com.cn/book/tupubarticle/29874
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)