版权声明:转载必须注明出处,违者必究。 https://blog.csdn.net/qq_41856518/article/details/84261124
刚刚在别人博客那里看到了字符串回文,以前没写,所以想写一下,顺便回忆一下栈的调用QAQ,都忘得差不多了。
字符串回文就是字符串对称,如s=“abbbddccddbbbba”,判断字符串是否回文很简单,就是从字符串头部(i++)和尾部(j--)同时扫描,如果i和j相遇前s[i]和s[j]一直相等,则字符串回文。
普通法直接上代码:
#include<iostream>
#include<string.h>
using namespace std;
const int maxsize=20;
int main()
{
char s[maxsize];
int len,flag;
while(1)
{
flag=1;
cin>>s;
len=strlen(s);
for(int i=0,j=len-1;i<(len-1)/2,j>(len-1)/2;i++,j--)
{
if(s[i]!=s[j]){flag=0;break;}
}
if(flag)cout<<"字符串回文"<<endl;
else cout<<"字符串不回文"<<endl;
}
}
运行结果:
下面来回忆一下调用栈来判断回文(注意:是调用栈)栈是先进后出,先把字符串入栈,然后一个个弹出来,注意,弹出来比较只需比较一半长度即可
#include<bits/stdc++.h>
#include<stack>
#include<string.h>
const int maxsize=20;
using namespace std;
int main()
{
stack<char>s;
int len,flag;
char str[maxsize];
while(1)
{
flag=1;
cin>>str;
len=strlen(str);
for(int i=0;i<=len-1;i++)
{
s.push(str[i]);
}
for(int i=0;i<=(len-1)/2;i++)
{
s.top();
if(s.top()!=str[i]){flag=0;break;}
s.pop();
}
if(flag)cout<<"字符串回文"<<endl;
else cout<<"字符串不回文"<<endl;
}
return 0;
}
运行结果: