算法:
递归法:对于序列A[0,n]]和B[0,m],LCS(A,B)无非三种情况
-
若A或B为空,则LCS为空,作为递归基
-
如果末字符相等,即A[n]=B[m]=‘X’,则取LCS(A[0,n),B[0,m))+‘X’,如果前者可以求解,则问题的规模被缩小
-
如果末字符不相等,即A[n]!=B[m],比如A[n]=a,B[m]=b,则a和b至多有一个会出现在最后的解里(对解有贡献)。因为比如a有贡献,那B在前[0,m)个字符里一定有a,之后A就结束了(a是A的最后一个字符),A中不可能再有b可以和B匹配。
当然可也能两者都不出现在最后的解里。
可以正向来做,最后把结果反过来
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string longerString(string A,string B);
string LCS(string A,string B);
string furtherLCS(string A,string B);
int main(int argc, char const *argv[])
{
cout<<LCS("educational","advantage");
return 0;
}
string longerString(string A,string B)
{
if(A.size()>B.size())
return A;
else return B;
}
string LCS(string A,string B)
{
string result=furtherLCS(A,B);
reverse(result.begin(), result.end());
return result;
}
string furtherLCS(string A,string B)
{
if(A.empty()||B.empty())
return "";
string A_cut,B_cut;
for(int i=0;i<A.size()-1;i++)
A_cut+=A[i];
for(int i=0;i<B.size()-1;i++)
B_cut+=B[i];
if(A[A.size()-1]==B[B.size()-1])
return A[A.size()-1]+furtherLCS(A_cut,B_cut);
return longerString(furtherLCS(A_cut,B),furtherLCS(B_cut,A));
}
试着用Python写了一下,十几行就完了
这才是程序员友好的语言
def longerString(a,b):
if len(a)>len(b):
return a
return b
def furtherLCS(a,b):
if len(a)==0 or len(b)==0:
return ""
elif a[-1]==b[-1]:
return a[-1]+furtherLCS(a[:len(a)-1],b[:len(b)-1])
return longerString(furtherLCS(a[:len(a)-1],b),furtherLCS(a,b[:len(b)-1]))
def LCS(a,b):
return furtherLCS(a,b)[::-1]
print(LCS("educational","advantage"))
也可以倒着来做
def longerString(a,b):
return a if len(a)>len(b) else b
def LCS(a,b):
return furtherLCS(a[::-1],b[::-1])[::-1]
def furtherLCS(a,b):
if len(a)==0 or len(b)==0:
return ""
elif a[0]==b[0]:
return a[0]+furtherLCS(a[1:],b[1:])
return longerString(furtherLCS(a,b[1:]),furtherLCS(a[1:],b))
print(LCS("educational","advantage"))