longest common substring

public static String lcs(String a, String b){
   int aLen = a.length();
   int bLen = b.length();
   if(aLen==0 || bLen==0)
        return "";

   if(a.charAt(aLen-1)==b.charAt(bLen-1))
   {
       return lcs(a.substring(0,aLen-1),b.substring(0.bLen-1))+a.charAt(aLen-1);
   }else{
       String x = lcs(a.substring(0,aLen-1),b);
       String y = lcs(a,b.substring(0,bLen-1));
       return (x.length()>=y.length()) ? x : y;
   }

}

dynamic programming.
public static String longestSubstring(String str1, String str2) {
 
StringBuilder sb = new StringBuilder();
if (str1 == null || str1.isEmpty() || str2 == null || str2.isEmpty())
  return "";
 
// ignore case
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
 
// java initializes them already with 0
int[][] num = new int[str1.length()][str2.length()];
int maxlen = 0;
int lastSubsBegin = 0;
 
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
  if (str1.charAt(i) == str2.charAt(j)) {
    if ((i == 0) || (j == 0))
       num[i][j] = 1;
    else
       num[i][j] = 1 + num[i - 1][j - 1];
 
    if (num[i][j] > maxlen) {
      maxlen = num[i][j];
      // generate substring from str1 => i
      int thisSubsBegin = i - num[i][j] + 1;
      if (lastSubsBegin == thisSubsBegin) {
         //if the current LCS is the same as the last time this block ran
         sb.append(str1.charAt(i));
      } else {
         //this block resets the string builder if a different LCS is found
         lastSubsBegin = thisSubsBegin;
         sb = new StringBuilder();
         sb.append(str1.substring(lastSubsBegin, i + 1));
      }
   }
}
}}
 
return sb.toString();
}

 


posted on 2014-07-20 10:35  brave_bo  阅读(121)  评论(0)    收藏  举报

导航