package Test;
public class MaxString{
/**
* find longest common sequence from two input string
* @param s1
* @param s2
* @return length of longest common sequence
*/
public static int LCS(String s1, String s2) {
int[][] c = new int[s1.length()][s2.length()];
// initialize the elements without top left element
for(int i=0; i<s1.length();i++){
if (s1.charAt(i) == s2.charAt(0)) {
c[i][0] = 1;
}
}
// sa nar
// 0 0 0
// 0 1 0
for(int j = 0; j<s2.length();j++){
if (s1.charAt(0) == s2.charAt(j)) {
c[0][j] = 1;
}
}
// sa nar
// 0 0 0
// 0 1 0
for (int i = 1; i < s1.length(); i++) {
for (int j = 1; j < s2.length(); j++) {
if (s1.charAt(i) == s2.charAt(j)) {
c[i][j] = c[i - 1][j - 1] + 1;
} else if (c[i][j - 1] > c[i - 1][j]) {
c[i][j] = c[i][j - 1];
} else {
c[i][j] = c[i - 1][j];
}
}
}
return c[s1.length() - 1][s2.length() - 1];
}
// 求解字符串中的最长重复子串
public static String maxRepat(String input) {
// 参数检查
if (input == null || input.length() == 0) {
return null;
}
// 重复子串的最长长度
int max = 0;
// 最长重复子串的起始位置
int first = 0;
int k = 0;
for (int i = 1; i < input.length(); i++) {
for (int j = 0; j < input.length() - i; j++) {
if (input.charAt(j) == input.charAt(i + j)) {
// hellowdhelloko 0 = 1 1 = 2 2 = 3 3 = 4
// 0 = 2 1= 3 2 = 4 3 = 5
// 0 = 3
k++;
} else {
k = 0;
}
if (k > max) {
max = k;
first = j - k + 1;
}
}
}
if (max > 0) {
System.out.println(max);
return input.substring(first, first + max);
}
return null;
}
public static void main(String[] args) {
String str1 = "hellowdhelloko";
String result = MaxString.maxRepat(str1);
System.out.println(result);
int s = MaxString.LCS("helldc","lohellc");
System.out.print(s);
}
}