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

利用栈后进先出的特点,将字符串的每个字符都入栈,再逐个出栈,可得到反读的字符串。可以利用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;
}
Solution3

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

Code
#include<iostream>
#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是回文串

猜你喜欢

转载自blog.csdn.net/buibuilili/article/details/107492586
今日推荐