给定一个 query 和一个 text,均由小写字母组成。要求在 text 中找出以同样的顺序连 续出现在 query 中的最长连续字母序列的长度。例如, query 为“acbac”,text 为 “acaccbabb”,那么 text 中的“cba”为最长的连续出现在 query 中的字母序列,因此, 返回结果应该为其长度 3。请注意程序效率。
思路:用一个矩阵来记录两个字符串中所有位置的两个字符之间的匹配情况,若是匹配则为1,否则为0。然后求出对角线最长的1序列,其对应的位置就是最长匹配子串的位置.
当字符匹配的时候,不是简单的给相应元素赋上1,而是赋上其左上角元素的值加1。我们用两个标记变量来标记矩阵中值最大的元素的位置,在矩阵生成的过程中来判断当前生成的元素的值是不是最大的,据此来改变标记变量的值,那么到矩阵完成的时候,最长匹配子串的位置和长度就已经出来了。
实例如下:
a c b a c
a 1 0 0 1 0
c 0 2 0 0 2
a 1 0 0 1 0
c 0 2 0 0 2
c 0 1 0 0 1
b 0 0 2 0 0
a 1 0 0 3 0
b 0 0 1 0 0
b 0 0 1 0 0
/**
* Created by Art on 2015/8/15.
*/
public class GetLCSLength {
public static void main(String[] args) {
String query = "acbac";
String text = "acaccbabb";
System.out.println(getLength(query,text));
}
public static int getLength(String query, String text){
char[] querys = query.toCharArray();
char[] texts = text.toCharArray();
int queryLength = querys.length;
int textLength = texts.length;
int[][] flags = new int[queryLength][textLength];
int result = 0;
for (int i = 0; i < queryLength; i++) {
for (int j = 0; j < textLength; j++) {
if(querys[i] == texts[j]){
if(i == 0 || j == 0)
flags[i][j] = 1;
else {
flags[i][j] = flags[i-1][j-1] + 1;
}
if(flags[i][j] > result)
result = flags[i][j];
}
}
}
return result;
}
}
结果:
3
http://my.oschina.net/gaosheng/blog/308853