java遞歸逆置一個字符串

忽然想到,遞歸逆置一個字符串的實現,應該仍是挺簡單的。spa

不過寫遞歸時總是會忘記return。code

//public String substring(int beginIndex)
//public String substring(int beginIndex, int endIndex)
//beginIndex -- 起始索引(包括), 索引從 0 開始。
//endIndex -- 結束索引(不包括)
public class Reverse {

    private static String tempStr="";
    public static String reverseStr(String str) {
        if (str.length() == 1 || str.length() == 0) {
            return tempStr+str;
        } else {
            tempStr += str.substring(str.length() - 1);  //截取獲得字符串的最後一個字符
            str = str.substring(0, str.length() - 1);  //除去當前字符串的最後一個字符
            return reverseStr(str);
        }
    }

    public static void main(String[] args) {
        String str = "ab";
        System.out.println("逆置前的字符串爲:"+str);
        System.out.println("逆置後的字符串爲:"+reverseStr(str));

    }

}
相關文章
相關標籤/搜索