【问题标题】:Recursive Method to return String with character at the start of the String递归方法在字符串的开头返回带有字符的字符串
【发布时间】:2018-12-23 11:31:27
【问题描述】:

这个问题不言自明...设计一个名为 startChar(String str, char c) 的方法。这是我在这里找到的代码,但它在字符串的末尾插入了字符。我不知道递归地思考。我理解这段代码,但对它的理解不足以操纵它在开头放置字符。任何形式的帮助表示赞赏。

示例输入:

startChar("Apple",'p')

输出:

ppale

代码

public static String chrToLast(String str, char ch) {
    //This if statement details the end condition
    if(str.length() < 1) {
        return "";
    }


     String newString = str.substring(1); //Create new string without first 
character

    if(str.indexOf(ch) == 0) { //This happens when your character is found
        return chrToLast(newString, ch) + ch;
    } else { //This happens with all other characters
        return str.charAt(0) + chrToLast(newString, ch);
    }
}

【问题讨论】:

  • 我不明白这段代码的用途;你能提供更多的例子吗? 为什么输出是"ppale"?
  • 我希望它返回Alepp。将角色的所有实例移动到最后的想法不是吗?所以p 字符都从原来的位置出来,走到了最后。
  • 哦,我明白了。您想反转它以便将字符移动到开头而不是结尾?所以预期的输出应该是ppAle,对吧?
  • 是的!例如考虑输入:(banana, a) 那么输出应该是 aaabnn。取所有 a's ,删除它们并将它们放在字符串的开头。
  • 请将所有解释和示例添加到帖子中,而不是作为 cmets。

标签: java string recursion methods char


【解决方案1】:

怎么样……

public static void main(String[] args) {
    String s = startChar("Apple", 'p');
    System.out.println("");
}

public static String startChar(String str, char ch) {
    return startChar(str,ch,"","");
}

private static String startChar(String str, char ch, String acc, String chs) {
    //This if statement details the end condition
    if (str.length() < 1) {
        return chs + acc;
    }


    String newString = str.substring(1); //Create new string without first character

    if(str.charAt(0) == ch) { //This happens when your character is found
        return startChar(newString, ch,acc, chs + ch);
    } else { //This happens with all other characters
        return startChar(newString, ch,acc+str.charAt(0), chs);
    }
}

这是带有辅助函数的递归

更新:你必须知道/记住你可以在递归调用之前和之后处理你的数据,但是尝试在最后编写你的递归调用,通常大多数语言在这种情况下都有优化。

在本例中,我们使用累加器来累加处理后的数据,然后在基本步骤中,我们将这些累加器处理为最终输出。

【讨论】:

  • 优秀的解决方案。我很难掌握递归,你似乎一时兴起想出了这个解决方案。我认为我的错是通过反复试验来思考,这种尝试和错误永远不会奏效。虽然是真的,但它使用的是辅助功能。
  • 很高兴得到诸如“优秀解决方案”之类的反馈。还请遵循关于what to do when someone answers 的 SO 准则
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
  • 2012-02-05
  • 2011-06-10
相关资源
最近更新 更多