Recursion - Double each char of a string input and cut of the last char afterwards with one method

烂漫一生 提交于 2019-12-25 18:41:42

问题


I have the following problem.

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?


回答1:


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 "";
}



回答2:


To do it in one function, just iterate over the string rather than calling another recursive function.

public static String doSomeMagic(String s) {
    String doubled = new String();
    if (s.length() == 0) return s;
    for(int i=0;i<s.length();i++)
        doubled += s.substring(i,i+1) + s.substring(i,i+1)
    return doubled + "\n" + doSomeMagic(s.substring(0, s.length()-1));
}



回答3:


Quick solution could be like

testMethod(string ip){
    if(ip.length()==1){
        ip=ip.toUppercase();
    }
    For(int i=0;i<ip.length()-1;i++){
        System.out.print(ip.charAt(i)+""+ip.charAt(i));
    }
    if(ip.length()>1){
        System. out. println();
        testMethod(ip.substring(1));
    }
}

Haven't tested it... But should work fairly



来源:https://stackoverflow.com/questions/22673377/recursion-double-each-char-of-a-string-input-and-cut-of-the-last-char-afterwar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!