1 递归,二分
private static String reverse(String s) {
int N = s.length();
if(N <= 1) return s;
String a = s.substring(0, N/2);
String b = s.substring(N/2, N);
return reverse(b) + reverse(a);
}
2 StringBuilder内置函数reverse()
public static String reverse(String str){
return new StringBuffer(str).reverse().toString();
}
实现原理:
public AbstractStringBuilder reverse() {
...
int n = count - 1;
// j初始化,长度-2再算术右移一位 j = (count-2)/2
// 偶数长度,遍历一半次数,对调替换
// 奇数长度,遍历一半-1次数,对调替换,中间值不用替换
for (int j = (n-1) >> 1; j >= 0; j--) {
int k = n - j;
char cj = value[j];
char ck = value[k];
value[j] = ck;
value[k] = cj;
...
}
...
return this;
}