码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-07-14 13:43:06      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:out   extra   names   oid   alpha   turn   car   tput   ++   

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;
}

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

标签:out   extra   names   oid   alpha   turn   car   tput   ++   

原文地址:https://www.cnblogs.com/solitude-cosmos/p/13298392.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!