java递归逆置一个字符串

原文链接: http://www.cnblogs.com/Guhongying/p/11129258.html

突然想到,递归逆置一个字符串的实现,应该还是挺简单的。

不过写递归时老是会忘记return。

//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));

    }

}

转载于:https://www.cnblogs.com/Guhongying/p/11129258.html

猜你喜欢

转载自blog.csdn.net/weixin_30611509/article/details/94943814