C++ 回文字符串

2020年5月20日 0 条评论 1.03k 次阅读 0 人点赞

回文字符串 (100 满分)

题目描述

若一个字符串的正序与倒序相同,则称其为回文字符串;现在给定一个字符串,使用递归的方法,判断他是否是回文字符串。

输入描述

字符串,长度不超过100000;

输出描述

若是,则输出"Yes."

若不是,则输出"No."

样例输入

abcadacba

样例输出

Yes.

方法一:

#include <iostream>
using namespace std;

bool huiwen(string s, int left, int right){
	if(s[left]!=s[right]){
		return false;
	}
	if(left==right||low==right-1){
		return true;
	}
	return huiwen(s, left+1, right-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;
}

参考:https://blog.csdn.net/vaemusicsky/java/article/details/81072503

方法二:

#include <iostream>
using namespace std;

string swapS(string s, string tmpS, int sizeS){
    if (sizeS < 1){
        return tmpS;
    }
    tmpS += s[sizeS-1];
    sizeS -= 1;
    return swapS(s, tmpS, sizeS);
}

int main(){
    string s,tmpS,swapped;
    cin >> s;
    swapped = swapS(s, tmpS, s.size());
    if(swapped==s){
        cout << "Yes.";
    }else{
        cout << "No.";
    }
    return 0;
}

2个都是 空间超限 ,不知道咋回事。

Sevenfal

这个人太懒什么东西都没留下

文章评论(0)