Longest common subsequence: Difference between revisions
Content deleted Content added
→{{header|D}}: ++ fortran |
→Recursion: Calculate len(a) and len(b) once each and reuse the value |
||
Line 268: | 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. |
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){ |
<lang java>public static String lcs(String a, String b){ |
||
int aLen = a.length(); |
|||
int bLen = b.length(); |
|||
if(aLen == 0 || bLen == 0){ |
|||
return ""; |
return ""; |
||
}else if(a.charAt( |
}else if(a.charAt(aLen-1) == b.charAt(bLen-1)){ |
||
return lcs(a.substring(0, |
return lcs(a.substring(0,aLen-1),b.substring(0,bLen-1)) |
||
+ a.charAt( |
+ a.charAt(aLen-1); |
||
}else{ |
}else{ |
||
String x = lcs(a, b.substring(0, |
String x = lcs(a, b.substring(0,bLen-1)); |
||
String y = lcs(a.substring(0, |
String y = lcs(a.substring(0,aLen-1), b); |
||
return (x.length() > y.length()) ? x : y; |
return (x.length() > y.length()) ? x : y; |
||
} |
} |