public static void long_comstr(String str) {
String[]s = new String[str.length()];
intmaxlen = 0, maxi = 0, temp;
//构建后缀数组
for(int i = 0; i < str.length(); i++) {
StringBuffersb = new StringBuffer();
for(int j = i; j < str.length(); j++) {
sb.append(str.charAt(j));
}
s[i]= sb.toString();
}
//对后缀数组排序
Arrays.sort(s);
//找到最长重复子串
for(int k = 0; k < s.length - 1; ++k) {
temp= comlen(s[k], s[k + 1]);
if(temp > maxlen) {
maxlen= temp;
maxi= k;
}
}
System.out.println("最长重复子串为" + s[maxi] + ",长度:" + maxlen);
}
//使用comlen()方法对数组进行扫描比较相邻元素,得到相邻字符串的最长相同字符的长度
public static int comlen(String p, String q) {
intcount = 0;
intlength = 0;
if(p.length() > q.length())
length= q.length();
else
length= p.length();
while(count < length && (p.charAt(count) == q.charAt(count)))
++count;
returncount;
}
使用后缀数组求字符串的最长重复子串
最新推荐文章于 2020-09-14 21:41:40 发布