回文字符串
题目描述
若一个字符串的正序与倒序相同,则称其为回文字符串;现在给定一个字符串,使用递归的方法,判断他是否是回文字符串。
输入描述
字符串,长度不超过100000;
输出描述
若是,则输出”Yes.”
若不是,则输出”No.”
样例输入
abcadacba
样例输出
Yes.
解法一://此算法空间消耗大
#include <iostream>
#include <string>
using namespace std;
bool huiwen(string s){
int n = s.size();
if(s[0]!=s[n-1]){
return false;
}
if(n==1||n==0){
return true;
}
s.erase(0, 1);//去除字符串首位
s.erase(n-2, n-1);//去除字符串末位
return huiwen(s);
}
int main(){
string s;
cin >> s;
bool res = huiwen(s);
if(res==1){
cout << "Yes." << endl;
}
else{
cout << "No." << endl;
}
return 0;
}
解法二:
#include <iostream>
#include <string>
using namespace std;
bool huiwen(string s, int low, int high){
if(s[low]!=s[high]){
return false;
}
if(low==high||low==high-1){
return true;
}
return huiwen(s, low+1, high-1);
}
int main(){
string s;
cin >> s;
int n = s.size();
bool res = huiwen(s, 0, n-1);
if(res==1){
cout << "Yes." << endl;
}
else{
cout << "No." << endl;
}
return 0;
}