zoukankan      html  css  js  c++  java
  • Common Subsequence

    Description
    A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = <x1, x2, ..., xm> another sequence Z = <z1, z2, ..., zk> is a subsequence of X if there exists a strictly increasing sequence <i1, i2, ..., ik> of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = <a, b, f, c> is a subsequence of X = <a, b, c, f, b, c> with index sequence <1, 2, 4, 6>. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y. 
    The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
    Input
    abcfbc abfcab programming contest abcd mnp
    Output
    4 2 0
    SampleInput
     1 #include<stdio.h>
     2 #include<string.h>
     3 #define max 505
     4 int main()
     5 {
     6     char s1[max],s2[max];
     7     int matrix[max][max],len1,len2;
     8     int i,j;
     9     while(scanf("%s%s",s1,s2)!=EOF)
    10     {
    11         len1=strlen(s1);
    12         len2=strlen(s2);
    13         for(i=0; i<=len1; i++)matrix[i][0]=0;
    14         for(j=0; j<=len2; j++)matrix[0][j]=0;
    15         for(i=1; i<=len1; i++)
    16         {
    17             for(j=1; j<=len2; j++)
    18             {
    19                 if(s1[i-1]==s2[j-1])
    20                 {
    21                     matrix[i][j]=matrix[i-1][j-1]+1;
    22                 }
    23                 else
    24                 {
    25                     if(matrix[i-1][j]>=matrix[i][j-1])
    26                     {
    27                         matrix[i][j]=matrix[i-1][j];
    28                     }
    29                     else
    30                     {
    31                         matrix[i][j]=matrix[i][j-1];
    32                     }
    33                 }
    34             }
    35         }
    36         printf("%d
    ",matrix[len1][len2]);
    37     }
    38     return 0;
    39 }
    View Code
    abcfbc abfcab
    programming contest 
    abcd mnp
    SampleOutput
    4
    2
    0
    题目大意:给出两个字符串,求两个字符串的最长公共字串。
  • 相关阅读:
    Linux scp、ssh命令
    Linux ps、top、free、uname命令
    适配器模式
    Linux不能进入图形化界面运行yum不管用
    SpringMVC 测试 mockMVC
    Idea和Git集成,并且Git管理不同的秘钥,idea分别提交项目到GitLab和GitHub
    多线程
    Java中Volatile关键字详解
    Spring事务管理--(二)嵌套事物详解
    jConsole, jVisualvm, btrace 区别和联系
  • 原文地址:https://www.cnblogs.com/to-creat/p/4891203.html
Copyright © 2011-2022 走看看