递归 - 将字符串输入的每个字符加倍,然后用一种方法剪切最后一个字符 [英] Recursion - Double each char of a string input and cut of the last char afterwards with one method

查看:55
本文介绍了递归 - 将字符串输入的每个字符加倍,然后用一种方法剪切最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.

递归方法 public static String doSomeMagic("Test") 应该返回:

The recursive method public static String doSomeMagic("Test") should return:

TTeesstt
TTeess
TTee
TT

我已经像这样实现了这个行为:

I've implemented this behaviour already like this:

public static String rowFunction(String s) {
    String toReturn = new String();

    if (!s.isEmpty()) {
        toReturn = String.valueOf(s.charAt(0));
        toReturn += toReturn + rowFunction(s.substring(1));
    }
    return toReturn;
}

public static String doSomeMagic(String s) {
    String toReturn = new String();

    if (!s.isEmpty()) {
        toReturn = rowFunction(s) + "\n" + doSomeMagic(s.substring(0, s.length() - 1));
    }
    return toReturn;
}

如何仅用一个功能来实现这一目标?有什么想法吗?

How can one achieve this with just one function? Any ideas?

推荐答案

我注意到您希望在没有循环的情况下在一个函数调用中完成此操作.你可能可以清理更多.这是:

I noticed you wanted to do this without a loop and in one function call. You can probably clean this up a lot more. Here it is:

public static String doSomeMagic(String s) {
    if (!s.isEmpty()) {
        StringBuffer sb = new StringBuffer();
        return sb.append(s.replaceAll("(\\S)", "$1$1"))
                 .append("\n")
                 .append(doSomeMagic( s.replaceAll(".$", "") )
                 .toString();
    }
    return "";
}

这篇关于递归 - 将字符串输入的每个字符加倍,然后用一种方法剪切最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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