1: public static final String tail1 = "$1";
2: public static final String tail2 = "$2";
3:
4: /**
5: * 求最长公共前缀LCP
6: *
7: * @param word1
8: * @param word2
9: * @return
10: */
11: public String getLCP(String word1, String word2) {
12: String res = "";
13: int len1 = word1.length();
14: int len2 = word2.length();
15: for (int i = 0; i < Math.min(len1, len2); i++) {
16: if (word1.charAt(i) == word2.charAt(i)) {
17: res += word1.charAt(i);
18: } else
19: break;
20: }
21: return res;
22: }
23:
24: /**
25: * 后缀数组方法求最长公共子串
26: *
27: * @param word1
28: * @param word2
29: * @return
30: */
31: public String getLCSByGST(String word1, String word2) {
32: String res = "";
33:
34: int len1 = word1.length();
35: int len2 = word2.length();
36: String gst[] = new String[len1 + len2];
37: for (int i = 0; i < len1; i++) {
38: gst[i] = mergeSuffix(word1.substring(i), word2);
39: }
40: for (int i = 0; i < len2; i++) {
41: gst[i + len1] = word2.substring(i) + tail2;
42: }
43: Arrays.sort(gst);
44: for (int i = 0; i < gst.length - 1; i++) {
45: String str = getLCP(gst[i], gst[i + 1]);
46: if (str.length() > res.length()) {
47: res = str;
48: }
49: }
50: if (res.endsWith("$"))
51: res = res.substring(0, res.length() - 1);
52: return res;
53: }
54:
55: private String mergeSuffix(String word1, String word2) {
56: StringBuffer sb = new StringBuffer();
57: sb.append(word1);
58: sb.append(tail1);
59: sb.append(word2);
60: sb.append(tail2);
61: return sb.toString();
62: }