Longest common subsequence: Difference between revisions

→‎Recursion: Calculate len(a) and len(b) once each and reuse the value
(→‎{{header|D}}: ++ fortran)
(→‎Recursion: Calculate len(a) and len(b) once each and reuse the value)
Line 268:
This is not a particularly fast algorithm, but it gets the job done eventually. The speed is a result of many recursive function calls.
<lang java>public static String lcs(String a, String b){
if(a.length()int aLen == 0 || ba.length() == 0){;
int bLen = b.length();
if(aLen == 0 || bLen == 0){
return "";
}else if(a.charAt(a.length()aLen-1) == b.charAt(b.length()bLen-1)){
return lcs(a.substring(0,a.length()aLen-1),b.substring(0,b.length()bLen-1))
+ a.charAt(a.length()aLen-1);
}else{
String x = lcs(a, b.substring(0,b.length()bLen-1));
String y = lcs(a.substring(0,a.length()aLen-1), b);
return (x.length() > y.length()) ? x : y;
}
Anonymous user