Java中的一个小递归问题

发布于 2024-10-29 00:03:55 字数 2190 浏览 0 评论 0原文

我目前正在解决一些递归问题,目前我陷入了困境。

到每个可能的位置,这样输出看起来像:

Input: ABCD
Out:
       ABCD
       A BCD
       A B CD
       A B C D
       A BC D
       AB CD
       AB C D
       ABC D

我目前已经解决了这个问题,并且达到了一个很像的点:

Input: ABCD
Out:
       ABCD
       A BCD
       A B CD
       A B C D

到目前为止我的问题代码:

import java.util.Scanner;

public class Words 
{
    static int counter = 0;
    static String fString = "";
    static String fString2 = "";
    static String previous = "";
    static String input = "";
    static String other = "";

    public static String segment(String inputPrefix, String restOfString)
{
    if(restOfString.length() != 0)
    {   
        if(inputPrefix.equals(""))
        {
            fString += restOfString + "\n";
            segment(restOfString.substring(0,1), restOfString.substring(1));
        }
        else
        {
            previous += inputPrefix + " ";
            fString += previous + restOfString + "\n";
            fString2 = previous + restOfString;
            segment(restOfString.substring(0,1)
                            , restOfString.substring(1));
        }
    }
    /*else
    {
        counter++;
        other = fString2.replaceAll(" ", "");
        System.out.println(other);
        if((counter + 1) < other.length())
        {
            System.out.println("Other: " + other);
            input = other.substring(0, counter + 1);
            other = other.substring(counter + 1);
            System.out.println(counter);
            System.out.println("input: " + input);
            System.out.print("other: " + other);

            segment(input, other);
        }
        else
            return fString;
    }*/

    return fString;

}

public static void main (String[] args) 
{
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String input = scan.next();
    System.out.println();
    System.out.println(segment("", input));

}
}

问题是递归地将空格插入到字符串中,插入 第二个 else 子句是我遇到最大麻烦的地方,因为每次我运行它时都没有注释它会进入无限循环。我什至放入了 int 跟踪语句(println 语句),但它仍然没有帮助。

我已经读了很多遍了,但我不明白为什么它不起作用。

I'm currently just working my way through some recursion problems, and I am currently stuck on one.

The problem is to recursively insert spaces into a string, into every single possible location, such that the output looks something like:

Input: ABCD
Out:
       ABCD
       A BCD
       A B CD
       A B C D
       A BC D
       AB CD
       AB C D
       ABC D

I have currently worked on the problem, and got to a point much like:

Input: ABCD
Out:
       ABCD
       A BCD
       A B CD
       A B C D

My code for the problem so far:

import java.util.Scanner;

public class Words 
{
    static int counter = 0;
    static String fString = "";
    static String fString2 = "";
    static String previous = "";
    static String input = "";
    static String other = "";

    public static String segment(String inputPrefix, String restOfString)
{
    if(restOfString.length() != 0)
    {   
        if(inputPrefix.equals(""))
        {
            fString += restOfString + "\n";
            segment(restOfString.substring(0,1), restOfString.substring(1));
        }
        else
        {
            previous += inputPrefix + " ";
            fString += previous + restOfString + "\n";
            fString2 = previous + restOfString;
            segment(restOfString.substring(0,1)
                            , restOfString.substring(1));
        }
    }
    /*else
    {
        counter++;
        other = fString2.replaceAll(" ", "");
        System.out.println(other);
        if((counter + 1) < other.length())
        {
            System.out.println("Other: " + other);
            input = other.substring(0, counter + 1);
            other = other.substring(counter + 1);
            System.out.println(counter);
            System.out.println("input: " + input);
            System.out.print("other: " + other);

            segment(input, other);
        }
        else
            return fString;
    }*/

    return fString;

}

public static void main (String[] args) 
{
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String input = scan.next();
    System.out.println();
    System.out.println(segment("", input));

}
}

That second else clause is where I am having my most trouble, because every time I run it un-commented it goes into an infinite loop. I even put int trace statements (the println statements) and it still isn't helping.

I've read through it many times and it just doesn't make sense to me why it doesn't work.

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

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

发布评论

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

评论(3

南七夏 2024-11-05 00:03:55

让我对你的代码产生怀疑的第一件事是你应该返回一系列字符串,但你的返回值是一个字符串。

也许,您应该确定您的基本情况和递归步骤。

看来您已经开始了解基本情况了。您可以在空字符串中插入零个空格,但是

allPossibleSpacings("") -> [ "" ]

您不想在末尾插入空格,因此您需要第二个基本情况

allPossibleSpacings("x") -> [ "x" ]

,然后您的递归步骤可能是

allPossibleSpacings("x" + s) -> flatten(
    ∀ t : allPossibleSpacings(s), ["x" + t, "x " + t])

我不会帮助您用Java编写它,因为这是家庭作业,但希望有所帮助。

The first thing that makes me dubious about your code is that you are supposed to returning a series of strings, but your return value is a string.

Perhaps, you should nail down your base case and recursive step.

It looks like you've got a start on the base case. You can insert zero spaces in the empty string, so

allPossibleSpacings("") -> [ "" ]

but you don't want to insert a space at the end, so you need a second base case

allPossibleSpacings("x") -> [ "x" ]

and then your recursive step could be

allPossibleSpacings("x" + s) -> flatten(
    ∀ t : allPossibleSpacings(s), ["x" + t, "x " + t])

I won't help you write that in Java since it's homework, but hope that helps.

心不设防 2024-11-05 00:03:55
void recurse(String myString, int start){
        System.out.println(myString);
        for(int i = start; i < myString.length; i++) {
            if (myString.charAt(i) != ' ' ){
                recurse(myString.Substring(0,i) + ' ' + myString.Substring(i), i+2);
            }
        }
    }

首先使用 recurse("ABCD", 1) 调用;

void recurse(String myString, int start){
        System.out.println(myString);
        for(int i = start; i < myString.length; i++) {
            if (myString.charAt(i) != ' ' ){
                recurse(myString.Substring(0,i) + ' ' + myString.Substring(i), i+2);
            }
        }
    }

call first with recurse("ABCD", 1);

吃颗糖壮壮胆 2024-11-05 00:03:55

看起来您已经能够正确进行第一个“分组”,但无法进行下一个分组。

分组为:“A BCD”、“AB CD”和“ABC D”。您需要将您的算法应用于每个分组。您已将其应用于第一个。你如何获得其余的?

已经过去足够的时间了吗?我写了一个 python 解决方案只是为了看看它与 Java 相比是什么样子。

def segment(input, separator=' ', start_from=0):
    print input
    # add spaces after each letter starting from start_from index, terminating at last letter-1
    for i in range(start_from, len(input)-1):
        # if the next letter is already a space, or this letter is a space, move on
        if separator in (input[i+1], input[i]): continue
        # whatever index we're on, do the next one recursively
        segment(input[:i] + input[i] + separator + input[i+1:], separator=separator, start_from=i+1)

segment('ABCD')

It looks like you've been able to do the first 'grouping' correctly, but unable to get the next groupings.

The groupings are: 'A BCD', 'AB CD', and 'ABC D'. You need to apply your algorithm to each of these groupings. You've applied it to the first. How do you get the rest of them?

Has enough time passed? I wrote up a python solution just to see what it'd look like compared to Java.

def segment(input, separator=' ', start_from=0):
    print input
    # add spaces after each letter starting from start_from index, terminating at last letter-1
    for i in range(start_from, len(input)-1):
        # if the next letter is already a space, or this letter is a space, move on
        if separator in (input[i+1], input[i]): continue
        # whatever index we're on, do the next one recursively
        segment(input[:i] + input[i] + separator + input[i+1:], separator=separator, start_from=i+1)

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