问题描述
完成一个递归程序,倒置字符数组。并打印实现过程
递归逻辑为:
当字符长度等于1时,直接返回
否则,调换首尾两个字符,在递归地倒置字符数组的剩下部分
输入格式
字符数组长度及该数组
输出格式
在求解过程中,打印字符数组的变化情况。
最后空一行,在程序结尾处打印倒置后该数组的各个元素。
样例输入
Sample 1
5 abcde
Sample 2
1 a
样例输出
Sample 1
ebcda
edcba
edcba
Sample 2
a
资源限制
时间限制:1.0s 内存限制:512.0MB
思路:每次递归,把最后一个字符和第一个字符交换,实现代码如下:
关键代码:
//开始进行交换
char temp = c[start];
c[start] = c[end];
c[end] = temp;
代码块:
import java.util.Scanner;
public class Main {
static String str;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
str = sc.next();
//把字符串转化为字符数组
char[]c = str.toCharArray();
System.out.println("\n"+f(str, c, 0, n-1, n, str));
}
static String f(String s, char[]c, int start, int end, int n, String len){
if(n == 1 || start >= end){
return s;
}
s = "";
//开始进行交换
char temp = c[start];
c[start] = c[end];
c[end] = temp;
//System.out.println(c[start]+" "+c[end]+"!!");
//打印每次交换的结果
for(int i = 0; i < len.length(); i++){
System.out.print(c[i]);
s += c[i];
}
System.out.println();
return f(s, c, start+=1, end-=1, n-=1, len);
}
}