动态规划法:
用二维矩阵来的每个元素来代表两个字符串的字符匹配情况,
LCS[i, j]= LCS[i-1, j-1] + 1 , if X[i-1] == Y[J-1].
LCS[i, j] =0, everything else
每一个元素记载着两个字符串的相似程度,而且每个元素只需关心上一个元素的值来计算字符串比较的累计情况。
实现代码:
public static string LongestCommonString(
string x,
string y)
{
if (x ==
null || y ==
null)
{
return null;
}
if (
string.IsNullOrEmpty(x) ||
string.IsNullOrEmpty(y))
{
return string.Empty;
}
int m =
x.Length;
int n =
y.Length;
int[,] LCS =
new int[m, n];
int result =
0;
int mIndex =
0;
int nIndex =
0;
for(
int i =
0; i < m; i++
)
{
for (
int j =
0; j < n; j++
)
{
if (i ==
0 || j ==
0)
{
LCS[i, j] =
0;
}
else if (x[i -
1] == y[j -
1])
{
LCS[i, j] =
1 + LCS[i -
1, j -
1];
if (result <
LCS[i, j])
{
result =
LCS[i, j];
mIndex =
i;
nIndex =
j;
}
}
}
}
StringBuilder sb =
new StringBuilder();
Stack<
char> stack =
new Stack<
char>
();
while(result >
0)
{
stack.Push(x[mIndex-
1]);
result = LCS[mIndex-
1, nIndex-
1];
mIndex--
;
nIndex--
;
}
while(stack.Count >
0)
{
sb.Append(stack.Pop());
}
return sb.ToString();
}
转载于:https://www.cnblogs.com/xuyanran/p/8594180.html