回文是指正读反读均相同的字符序列。如"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是回文串
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)