我目前正在努力解决一些递归问题,而且我目前只停留在一个。
问题是递归地将空格插入到字符串中,放入每个可能的位置,这样输出看起来像:
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));
}
}
第二个其他条款是我最麻烦的地方,因为每次我运行它都没有评论它进入无限循环。我甚至把int trace语句(println
语句)放了,但它仍然没有帮助。
我已经多次阅读了它,这对我来说没有意义,为什么它不起作用。
答案 0 :(得分:4)
让我怀疑你的代码的第一件事是你应该返回一系列字符串,但你的返回值是一个字符串。
也许,你应该确定基础案例和递归步骤。
看起来你已经开始了基础案例。您可以在空字符串中插入零空格,所以
allPossibleSpacings("") -> [ "" ]
但你不想在最后插入一个空格,所以你需要一个第二个基本案例
allPossibleSpacings("x") -> [ "x" ]
然后你的递归步骤可能是
allPossibleSpacings("x" + s) -> flatten(
∀ t : allPossibleSpacings(s), ["x" + t, "x " + t])
我不会帮你用Java编写它,因为它是作业,但希望有所帮助。
答案 1 :(得分:3)
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);
答案 2 :(得分:2)
看起来你已经能够正确地进行第一次'分组',但无法进行下一次分组。
分组为:'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')