c++判断字符串是否为回文

回文是指正读反读均相同的字符序列。如"abba"和”abdba”均是回文,但"good"不是回文。

Solution1

使用reverse()函数将字符串反转,与原字符串比较,若相同,则是回文,否则不是。例如:将"abba"反转得到"abba",和原字符串相同。将"good"反转得到"doog",和原字符串不同。

Code
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
	string a;
	cin >> a;
	string b = a;
	reverse(b.begin(), b.end());//反转字符串
	if (a == b) cout << a << "是回文串" << endl;
	else cout << a << "不是回文串" << endl;
	return 0;
}
Solution2

利用双指针,从两边往中间扫

Code1
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	string a;
	cin>>a;
	string b=a;
	int l=0,r=b.length()-1;
    while(l<r){
        swap(b[l],b[r]);
        l++;r--;
    }
    if (a == b) cout << a << "是回文串" << endl;
    else cout << a << "不是回文串" << endl;
	return 0;
}
Code2
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	string a;
	cin>>a;
	int l=0,r=a.length()-1;
    while(l<r){
        if(a[l] != a[r]) break;
        l++;r--;
    }
    if (l < r) cout << a << "不是回文串" << endl;
    else cout << a << "是回文串" << endl;
	return 0;
}
Solution3

利用栈后进先出的特点,将字符串的每个字符都入栈,再逐个出栈,可得到反读的字符串。可以利用STL库的stack,方便实现。

Code
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
int main() {
	stack<char> p;
	string a;
	cin >> a;
	for (int i = 0; i < a.length(); i++) p.push(a[i]); //入栈
	string b;
	while (!p.empty()) {//判断栈非空
		 b += p.top();  //取栈顶元素
		 p.pop();       //栈顶元素出栈
	}
	if (a == b) cout << a << "是回文串" << endl;
	else cout << a << "不是回文串" << endl;
	return 0;
}
Solution4

最近在看数据结构的书,所以自己实现了一下链栈(STL它不香吗

Code
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
struct Node
{
 	char data;
 	Node* next;
};
void great_list(Node*& head)  //创建空链表无头结点
{
    head = NULL;
}
void set_list(Node*& head,string s) { //将一个字符串的每个字符入栈
 	Node* p;
 	for (int i = 0; i < s.length(); i++) {
  		p = new Node;
  		p->data = s[i];
  		p->next = head;
  		head = p;
 	}
}
void pop(Node*& head) {//栈顶元素出栈
 	Node* p = head;
 	head = head->next;
 	delete p;
}
char top(Node*& head) { //取栈顶
 	if (head) return head->data;
}
int main() {
 	Node* head;
 	great_list(head);
 	string a;
 	cin >> a;
	string b;
	set_list(head, a);//入栈
	while (head){//判断栈非空
	  	b += top(head);//取栈顶元素
	  	pop(head);//栈顶元素出栈
	}
	if (a == b) cout <<a<< "是回文串" << endl;
	else cout <<a<< "不是回文串" << endl;
	return 0;
}
Sample
abbba
abbba是回文串
  • 83
    点赞
  • 282
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值