选几种典型的加以说明
import java.io.BufferedInputStream;
import java.util.Scanner;
public class test {
// 不返回串
public static void reversePrint(String s, int i) {
if (i != s.length()) {
reversePrint(s, i + 1);
System.out.print(s.charAt(i));
}
}
// 返回串
public static String reverseString(String s, int i) {
if (i == s.length()) {
return "";
} else {
String s1 = reverseString(s, i + 1);
return s1 + s.charAt(i);
}
}
// 返回串
public static String reverseString1(String s) {
int N = s.length();
if (N <= 1) {
return s;
}
String s1 = s.substring(0, N / 2);
String s2 = s.substring(N / 2, N);
return reverseString1(s2) + reverseString1(s1);
}
// 返回串,系统自带方法就是这样实现的,测试结果也是这种方法最快
public static String reverseString2(String s) {
int N = s.length() - 1;
char[] c = s.toCharArray();
for (int j = (N - 1) >> 1; j >= 0; --j) {
int k = N - j;
char ck = c[j];
c[j] = c[k];
c[k] = ck;
}
return new String(c);
}
public static void main(String[] args) {
Scanner cin = new Scanner(new BufferedInputStream(System.in));
String s = cin.next();
cin.close();
long l1 = System.nanoTime();
reversePrint(s, 0); // 直接打印
long e1 = System.nanoTime();
System.out.println();
System.out.println((e1-l1)+"ns");
System.out.println();
long l2 = System.nanoTime();
System.out.println(reverseString(s, 0)); // 直接递归到底层返回逆序回串
long e2 = System.nanoTime();
System.out.println((e2-l2)+"ns");
System.out.println();
long l3 = System.nanoTime();
System.out.println(reverseString1(s)); // 二分递归到底层返回逆序串
long e3 = System.nanoTime();
System.out.println((e3-l3)+"ns");
System.out.println();
long l4 = System.nanoTime();
System.out.println(reverseString2(s)); // 和java的StringBuilder一样的实现
long e4 = System.nanoTime();
System.out.println((e4-l4)+"ns");
System.out.println();
}
}
综上所述,最后一种方法最好,StringBuilder自带的reverse也是这样实现的