回文字符串(递归/非递归)

Posted solitude-cosmos

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了回文字符串(递归/非递归)相关的知识,希望对你有一定的参考价值。

FJ的字符串
 

Description

 

FJ在沙盘上写了这样一些字符串:  A1 = “A”  A2 = “ABA”  A3 = “ABACABA”  A4 = “ABACABADABACABA”  … …  你能找出其中的规律并写所有的数列AN吗?

 

Input

 

仅有一个数:N ≤ 26。

 

Output

 

请输出相应的字符串AN,以一个换行符结束。输出中不得含有多余的空格或换行、回车符。

 

Sample Input 1 

3

Sample Output 1

ABACABA
Solution
非递归

#include<iostream>
using namespace std;

string f[10001];
string alpha[26] = { "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z" };

void recurse(int n) {
  for (int i = 1;i <= n;i++) {
    if (i == 1)
      f[i] = "A";
    else {
      f[i] = f[i - 1] + alpha[i - 1] + f[i - 1];
    }
  }

}

int main() {
  int N;
  scanf("%d", &N);
  recurse(N);
  cout << f[N] << endl;
  return 0;
}

递归

#include<iostream>
using namespace std;


string alpha[26] = { "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z" };

string recurse(int n) {
  if (n == 1) {
    return "A";
  }
  else {
    return recurse(n-1)+ alpha[n - 1] + recurse(n - 1);
  }
}


int main() {
  int N;
  string result;
  scanf("%d", &N);
  result=recurse(N);
  cout << result << endl;
  return 0;
}

以上是关于回文字符串(递归/非递归)的主要内容,如果未能解决你的问题,请参考以下文章

使用 JavaScript 进行递归回文检查

Java 用递归判断字符串是否可以回文

递归算法的空间复杂度

递归判断字符串是否为回文

使用 C 中的递归函数测试回文

用递归调用来判断字符串是否是回文