我正在尝试创建一个递归算法,确定String c是否是字符串a和b的有序shuffle。有序shuffle意味着String c是通过散布字符串a和b的字符组成的,其方式仍然保持两个字符串的从左到右的顺序。
我尝试过这个算法的代码并且它在某种程度上起作用,但是当我尝试测试某个混洗的单词时我遇到了一个问题,如下面的代码所示。我认为这与我的if语句中的索引错误有关,但无法找到修复此语句的方法或绕过它,任何反馈或指导都将非常感激。
public class StringShuffleTest {
public static boolean isOrderedShuffle(String a, String b, String c){
//boolean to determine if String c is an ordered shuffle.
boolean isShuffled = false;
//variables for the size of Strings a, b and c.
int n = a.length();
int m = b.length();
int len = c.length();
//if the length of c is not the length of a + b return false.
if (len != (n + m)){
return isShuffled;
}
//if the length of a or b is 0, and c equals a or b, return true, otherwise,
//return false.
if (n == 0 || m == 0){
if (c.equals(a) || c.equals(b)){
return true;
}
else
return isShuffled;
}
//if String a has length 1, remove String a from String c and make String a empty.
if (n == 1){
c = c.substring(0, c.indexOf(a.charAt(0))) + c.substring(c.indexOf(a.charAt(0)) +1);
a = "";
return isOrderedShuffle(a, b, c);
}
else
//Recursive algorithm to determine if String c is an ordered shuffle of a and b.
if (c.indexOf(a.charAt(0)) >= 0){
int indexOfFirst = c.indexOf(a.charAt(0));
int indexOfSecond = c.indexOf(a.charAt(1));
if (indexOfFirst <= indexOfSecond){
c = c.substring(0, indexOfFirst) + c.substring(indexOfFirst +1);
a = a.substring(1, n);
System.out.println(a);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
else
return isShuffled;
}
return isShuffled;
}
public static void main(String[] args) {
System.out.println(StringShuffleTest.isOrderedShuffle("castle", "cat", "catcastle"));
}
}
答案 0 :(得分:2)
您可以通过创建一个调用递归方法的方法来简化这一过程,例如:
private static String a, b, c;
public static boolean isOrderedShuffle(String a, String b, String c) {
if (a.length() + b.length() != c.length())
return false;
StringShuffleTest.a = a; StringShuffleTest.b = b; StringShuffleTest.c = c;
return isOrderedShuffle(0, 0);
}
private static boolean isOrderedShuffle(int n, int m) {
if (n + m == c.length())
return true;
if (n < a.length() && a.charAt(n) == c.charAt(n + m) && isOrderedShuffle(n + 1, m))
return true;
if (m < b.length() && b.charAt(m) == c.charAt(n + m) && isOrderedShuffle(n, m + 1))
return true;
return false;
}