The problem I'm working on is here: http://practiceit.cs.washington.edu/problem/view/cs2/sections/recursivebacktracking/longestCommonSubsequence
basically we are given two strings and we are requested to find the longest common subsequence. I've searched for solutions online and compared them to my own solution, and I couldn't find any bugs in my code. I wonder why it still wouldn't work.
And also, I was requested to solve this problem by using recursive methods
Here's my code:
public static String longestCommonSubsequence(String a, String b){
if(a.isEmpty() || b.isEmpty()){
return "";
}
if (a.substring(a.length() - 1).equals(b.substring(b.length() - 1))){
return longestCommonSubsequence(a.substring(0, a.length() - 1), b.substring(0, b.length()
- 1)) + a.substring(a.length() - 1);
} else {
String first = longestCommonSubsequence(a, b.substring(b.length() - 1));
String second = longestCommonSubsequence(a.substring(a.length() - 1), b);
if(first.length() > second.length()){
return first;
}
return second;
}
}
And here are all the test cases:
Call Value Returned
"ABCDEFG", "BGCEHAF" "BCEF"
"she sells", "seashells" "sesells"
"12345", "54321 21 54321" "123"
"supercilious teacher", "delicious peach" "ecious each"
"Marty", "Helene" ""
"","Joe" ""
"Suzy", "" ""
"ACGGTGTCGTGCTA", "CGTTCGGCTATCGTACGT" "CGGTTCGTGT"
with my code I got StackOverFlow for all the test cases.