所以我在Stack Overflow上看到,可以使用不使用递归的方法派生通用后缀。我很好奇能否通过递归实现相同的目标。尝试使用下面的代码,但得到java.lang.StackOverflowError。有人可以帮忙吗?
public static String commonSuffixWithRecursion(String s1, String s2) {
if(s1.length()==0 || s2.length()==0) {
return "Strings are empty";
}
if(s1.charAt(s1.length()-1)==s2.charAt(s2.length()-1)) {
return s1.length()-1 + commonSuffixWithRecursion(s1,s2);
}
return "No common Suffix";
}
答案 0 :(得分:1)
没有通用后缀时,应返回空字符串。
您可以使用subString
获取下一轮的输入
当前字符应在下一次漫游结果后的之后后添加
示例代码:
public static String commonSuffixWithRecursion(String s1, String s2) {
if (s1.length() == 0 || s2.length() == 0) {
return "";
}
if (s1.charAt(s1.length() - 1) == s2.charAt(s2.length() - 1)) {
String nextS1 = s1.substring(0, s1.length() - 1);
String nextS2 = s2.substring(0, s2.length() - 1);
return commonSuffixWithRecursion(nextS1, nextS2 ) + s1.charAt(s1.length() - 1);
}
return "";
}
测试用例:
public static void main(String[] args) {
System.out.println(commonSuffixWithRecursion("dbc", "abc")); // bc
System.out.println(commonSuffixWithRecursion("a", "a")); // a
System.out.println(commonSuffixWithRecursion("ab", "b")); // b
System.out.println(commonSuffixWithRecursion("a", "b")); // empty
}
答案 1 :(得分:1)
一种简单的递归方法是
public static String commonSuffixWithRecursion(String x, String y, int m, int n) {
if(m <= 0 || n <= 0)
return "";
if (x.charAt(m-1) == y.charAt(n-1))
return commonSuffixWithRecursion(x, y, m-1, n-1) + x.charAt(m-1);
else
return "";
}
这里m=x.length() and n=y.length()
答案 2 :(得分:0)
这是后缀大小增加的另一种选择:
public static String commonSuffixWithRecursion(String s1, String s2, int suffixSize) {
int i1 = s1.length() - suffixSize;
int i2 = s2.length() - suffixSize;
if (i1 > -1 && i2 > -1 && s1.charAt(i1) == s2.charAt(i2)) {
return commonSuffixWithRecursion(s1, s2, suffixSize + 1);
}
return s1.substring(i1 + 1);
}
以下是一些测试用例:
public static void main(String[] args) {
System.out.println(commonSuffixWithRecursion("dbc", "abc", 1)); // bc
System.out.println(commonSuffixWithRecursion("a", "a", 1)); // a
System.out.println(commonSuffixWithRecursion("ab", "b", 1)); // b
System.out.println(commonSuffixWithRecursion("a", "b", 1)); // empty
System.out.println(commonSuffixWithRecursion("a", "bc", 1)); // empty
System.out.println(commonSuffixWithRecursion("ac", "bc", 1)); // c
System.out.println(commonSuffixWithRecursion("ac", "bcd", 1)); // empty
System.out.println(commonSuffixWithRecursion("", "bcd", 1)); // empty
System.out.println(commonSuffixWithRecursion("bcd", "bcd", 1)); // bcd
}