AAndApp2.java package algorithms;public class AAndApp { public static void main(String[] args) { self1(); System.out.println(reverseString(null)); } private static void self1() { //去掉空格 String a = " a bb d dd "; char[] b = a.toCharA
package algorithms;
public class AAndApp {
public static void main(String[] args) {
self1();
System.out.println(reverseString(null));
}
private static void self1() {
//去掉空格
String a = " a bb d dd ";
char[] b = a.toCharArray();
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < b.length; i++){
if ( 32 != b[i]){
sb.append(b[i]);
}
}
System.out.println(sb.toString());
System.out.println(sb.reverse());
}
//反转字符串:最好的方法是StringBuffer中的inverse方法
public static String reverseString(String s) {
if (null == s || s.isEmpty()){
return s;
}else {
return reverseString(s.substring(1)) + s.charAt(0);
}
}
}
好玩的递归
String反转的本质是什么AAndApp1.java
package algorithms;
import javax.sound.midi.SoundbankResource;
import java.util.Arrays;
public class AAndApp1 {
public static void main(String[] args) {
System.out.println(reverse("abcdefgh"));
}
private static String reverse(String n){
if (null == n || n.isEmpty()){
return n;
}
return reverse(n.substring(1)) + n.charAt(0) + (n.substring(1)) + '\\';
//结果是:h\gh\fgh\efgh\defgh\cdefgh\bcdefgh\abcdefgh\,其中的奥秘就在reverse(n.substring(1))
//和n.charAt(0)位置的次序。
}
}
