Java中递归删除字符

发布于 2025-01-02 21:16:38 字数 578 浏览 0 评论 0原文

作为练习,下面的代码块旨在递归地遍历字符串并删除所有“x”字符。它确实做到了这一点,但我想跟踪 newStr 而不将其作为方法中的参数传递。有没有办法将其移动到方法体中?

谢谢!

public static String deathToX(String str, String newStr) {  
    //look for x char
    if(str.substring(0, 1).equals("x")) {
        //do nothing
    } else {
        //add non-x char to newStr
        newStr += str.charAt(0);
    }

    if(str.length() == 1) {
        return newStr;
    }

    return deathToX(str.substring(1), newStr);
}

public static void main(String[] args) {
    System.out.println("Return: " + deathToX("xnoxmore", ""));
}

As an exercise, the code block below intends to recursively go through a string and remove all the of the "x" characters. It does that, but I would like to keep track of the newStr without passing it as a parameter in the method. Is there anyway to move it into the method body?

Thanks!

public static String deathToX(String str, String newStr) {  
    //look for x char
    if(str.substring(0, 1).equals("x")) {
        //do nothing
    } else {
        //add non-x char to newStr
        newStr += str.charAt(0);
    }

    if(str.length() == 1) {
        return newStr;
    }

    return deathToX(str.substring(1), newStr);
}

public static void main(String[] args) {
    System.out.println("Return: " + deathToX("xnoxmore", ""));
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

深海不蓝 2025-01-09 21:16:39

我想跟踪 newStr,而不将其作为方法中的参数传递。

为什么?在函数式递归编程中通常需要将中间结果传递给函数。我所做的是创建一个处理大量工作并接受累加器的函数,并创建一个包装函数,使用所需的起始值调用前一个函数:

private static String deathToX0(String str, String newStr) {
    // the original implementation
}

public static String deathToX(String str) {
    return deathToX(str, "");
}

顺便说一句,您可能不想使用 String 为中间结果,因为涉及复制。 StringBuilder 会更快。

I would like to keep track of the newStr without passing it as a parameter in the method.

Why? Passing the intermediary result into the function is often required in functional-style recursive programming. What I do is make a function that handles the bulk of the work and accepts the accumulator, and make a wrapper function that calls the previous one with the required starter value:

private static String deathToX0(String str, String newStr) {
    // the original implementation
}

public static String deathToX(String str) {
    return deathToX(str, "");
}

As an aside, you might not want to use a String for the intermediate result because of the copying involved. A StringBuilder would be faster.

独享拥抱 2025-01-09 21:16:39

简短的答案是肯定的......通常在树的递归过程中,您可以计算出每个级别的位(在本例中为空白或当前字符)。因此,return 语句应该递归地调用自身,然后在树的底部,通过将每个级别的部分相加来重建您想要的答案。

public static String deathToX(String str){
    if (!str.isEmpty()){
        return (str.substring(0, 1).equals("x") ? "" : str.substring(0, 1)) + deathToX(str.substring(1));
    }else{
        return "";
    }
}

public static void main(String[] args){
    System.out.println("Return: " + deathToX("xnoxmore"));
}

在上面的示例中,我使用简写 if 格式将其全部放在一行中,但您可以将其展开。您应该能够看到递归函数在 return 语句上递归,并且我为最后一级添加了特殊情况。如果您要将其拆分并将此级别的答案放入局部变量(例如 tmp)中,那么您将使用:

return tmp + deathToX(str.substring(1));

记住递归意味着当前执行只会暂停,直到较低的执行完成,这样您就可以愉快地存储信息以在备份时恢复。希望这有帮助:)

The short answer is yes... with recursion typically on the way down the tree you work out the bit at each level in this case blank or the current character. So the return statement should call itself recursively then at the bottom of the tree the answer you wanted is reconstructed by adding together the sections at each level.

public static String deathToX(String str){
    if (!str.isEmpty()){
        return (str.substring(0, 1).equals("x") ? "" : str.substring(0, 1)) + deathToX(str.substring(1));
    }else{
        return "";
    }
}

public static void main(String[] args){
    System.out.println("Return: " + deathToX("xnoxmore"));
}

In the sample above I used the shorthand if format to put it all on one line but you could expand it out. You should be able to see that the recursive function recurses on the return statement and I put in a special case for the last level. If you were to split it and put this levels answer in a local variable e.g. tmp then you would use:

return tmp + deathToX(str.substring(1));

Remember recursion means that the current execution is only paused until the lower ones finish so you can happily store info to recover on your way back up. Hope this helps :)

我纯我任性 2025-01-09 21:16:39
public class solution {

    // Return the changed string
    public static String removeX(String input){
    if(input.equals("") || input.equals("x"))
            return "";

        String returnStr="";
        removeX(input.substring(1));
        for(int i=0;i<input.length();i++)
        {
            if(input.charAt(i)=='x')
                continue;
            else
                returnStr+=input.charAt(i);
        }
        return returnStr;
    }
}

这是我的方法。这段代码转到字符串的末尾,如果它得到 X 作为最后一个字符串,它返回“”(什么也没有),然后它检查整个子字符串中的“x”,如果它出现在字符串中,它将继续,否则它会将剩余字符附加到该字符串并继续。
最后返回更新后的字符串。!
希望这有帮助..!!好吧,这是我在这里的第一个贡献:)

public class solution {

    // Return the changed string
    public static String removeX(String input){
    if(input.equals("") || input.equals("x"))
            return "";

        String returnStr="";
        removeX(input.substring(1));
        for(int i=0;i<input.length();i++)
        {
            if(input.charAt(i)=='x')
                continue;
            else
                returnStr+=input.charAt(i);
        }
        return returnStr;
    }
}

This is my approach. This code goes to the end of the string, if it gets X as last string, it returns ""(nothing), then it checks the whole substring for "x", if its present in the string, it will continue, else it will append rest character to that string and it goes on.
Finally returns the updated string.!
Hope this helps..!! well, this is my first contribution here :)

神爱温柔 2025-01-09 21:16:38

好吧,您可以将代码更改为:

public static String deathToX(String str)
{   
    // Termination case
    if (str.length() == 0)
    {
        return str;
    }
    // Work out whether or not we want the first character
    String prefix = str.startsWith("x") ? "" : str.substring(0, 1);

    // Let the recursive call handle the rest of the string, and return
    // the prefix (empty string or the first character) followed by the
    // x-stripped remainder.
    return prefix + deathToX(str.substring(1));
}

这是您正在考虑的事情吗?

当然,这是一种极其低效的字符串操作方式,但我假设您对事物的递归性质更感兴趣。

Well, you could change the code to:

public static String deathToX(String str)
{   
    // Termination case
    if (str.length() == 0)
    {
        return str;
    }
    // Work out whether or not we want the first character
    String prefix = str.startsWith("x") ? "" : str.substring(0, 1);

    // Let the recursive call handle the rest of the string, and return
    // the prefix (empty string or the first character) followed by the
    // x-stripped remainder.
    return prefix + deathToX(str.substring(1));
}

Is that the sort of thing you were thinking of?

Of course, this is a horribly inefficient way of doing string manipulation, but I assume you're more interested in the recursive nature of things.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文