Skip to content

Instantly share code, notes, and snippets.

@weidagang
Last active January 1, 2016 18:09
Show Gist options
  • Select an option

  • Save weidagang/8182284 to your computer and use it in GitHub Desktop.

Select an option

Save weidagang/8182284 to your computer and use it in GitHub Desktop.
Longest Common Substring
public class LCS {
public static void main(String... args) throws Exception {
System.out.println(lcs("Milexxs", "xxxxxxxM"));
}
public static String lcs(String a, String b) {
if (null == a || null == b) return "";
String longest = "";
for (int i = 0; i < a.length(); ++i) {
for (int j = 0; j < b.length(); ++j) {
int k;
for (k = 0; i + k < a.length() && j + k < b.length(); ++k) {
if (a.charAt(i+k) != b.charAt(j+k)) {
break;
}
}
if (k > longest.length()) {
longest = a.substring(i, i + k);
}
}
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment