So I have seen on Stack Overflow that common suffix can be derived using methods which do not use recursion. I was curious if i could achieve the same with recursion. Tried with below code but getting java.lang.StackOverflowError. Can someone help?
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";
}
It should return empty string when there is not common suffix.
You can use subString
to get the input for next round
Current char should be appended after the result of next rount
Sample code:
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 "";
}
Test case:
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
}
One simple way to do it recursively is
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 "";
}
Here m=x.length() and n=y.length()
Here is another option using an incremented suffix size:
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);
}
Here are some test cases:
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.