在 Java 中递归反转字符串的最佳方法是什么? [英] Whats the best way to recursively reverse a string in Java?

查看:27
本文介绍了在 Java 中递归反转字符串的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天一直在搞递归.通常是一种使用得不够多的编程技术.

I have been messing around with recursion today. Often a programming technique that is not used enough.

我开始递归地反转一个字符串.这是我想出的:

I set out to recursively reverse a string. Here's what I came up with:

//A method to reverse a string using recursion
    public String reverseString(String s){
        char c = s.charAt(s.length()-1);
        if(s.length() == 1) return Character.toString(c);   

        return c + reverseString(s.substring(0,s.length()-1));
    }

我的问题:Java 中有更好的方法吗?

My question: is there a better way in Java?

推荐答案

最好的方法是不要使用递归.这些东西通常用于教学生递归概念,而不是实际的最佳实践.所以你这样做的方式很好.只是不要在 Java 中对现实世界的应用程序中的这些东西使用递归;)

The best way is not to use recursion. These stuff are usually used to teach students the recursion concept, not actual best practices. So the way you're doing it is just fine. Just don't use recursion in Java for these kind of stuff in real world apps ;)

附注.除了我刚才所说的,我会选择 "" 作为我的递归函数的基本情况:

PS. Aside what I just said, I'd choose "" as the base case of my recursive function:

public String reverseString(String s){
    if (s.length() == 0) 
         return s;

    return reverseString(s.substring(1)) + s.charAt(0);
}

这篇关于在 Java 中递归反转字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆