- packagecom.eshore.sweetop.dynamicprogramming;
- publicclassLCS{
- publicstaticvoidLCSLength(char[]x,char[]y){
- intm=x.length;
- intn=y.length;
- int[][]c=newint[m+1][n+1];
- char[][]b=newchar[m+1][n+1];
- for(inti=1;i<=m;i++){
- c[i][0]=0;
- }
- for(inti=1;i<n;i++){
- c[0][i]=0;
- }
- for(inti=1;i<=m;i++){
- for(intj=1;j<=n;j++){
- if(x[i-1]==y[j-1]){
- c[i][j]=c[i-1][j-1]+1;
- b[i][j]='※';
- }elseif(c[i-1][j]>=c[i][j-1]){
- c[i][j]=c[i-1][j];
- b[i][j]='↑';
- }else{
- c[i][j]=c[i][j-1];
- b[i][j]='←';
- }
- }
- }
- display(b,x,m,n);
- }
- publicstaticvoiddisplay(char[][]b,char[]x,inti,intj){
- if(i==0||j==0){
- return;
- }
- if(b[i][j]=='※'){
- display(b,x,i-1,j-1);
- System.out.print(x[i-1]);
- }elseif(b[i][j]=='↑'){
- display(b,x,i-1,j);
- }else{
- display(b,x,i,j-1);
- }
- }
- publicstaticvoidmain(String[]args){
- char[]a={'A','B','C','B','D','A','B'};
- char[]b={'B','D','C','A','B','A'};
- LCS.LCSLength(a,b);
- System.out.println();
- LCS.LCSLength(b,a);
- }
- }
算法之LCS
最新推荐文章于 2025-03-19 17:55:16 发布