zoukankan      html  css  js  c++  java
  • 最长公共子串和最长公共序列

    1. 最长公共子串

    注意子串是连续的。有下列动态转移方程

    c[i][j] = c[i-1][j-1] + 1   when X[i] = Y[j]

    c[i][j] = 0   when X[i] != Y[j]

     1 int c[100][100];
     2 
     3 int LCS(char x[], int len_x, char y[], int len_y){
     4 
     5        int max_len = 0;
     6 
     7        for(int i =0; i < len_x ; i++){
     8            for(int j = 0; j < len_y;  j++){
     9                  if(x[i] == y[j]){
    10                       if(i && j)
    11                           c[i][j] = c[i-1][j-1] + 1;
    12                       if(i == 0 || j == 0)
    13                           c[i][j] = 1;
    14                       if(c[i][j] > max_len)
    15                            max_len = c[i][j];
    16                 }
    17            }
    18       }
    19 
    20       return max_len;
    21 }    

    2. 最长公共子序列

    子序列不要求连续。

    有下列状态转移方程

    c[i][j] = c[i-1][j-1] + 1 if x[i] == y[j]

    c[i][j] = max{c[i-1][j], c[i][j-1]} if x[i] != y[j]

    // x = "AB"   y = "CD"
    
    int c[100][100] = 0;
    
    int lcs(char x[], char y[]){
         int m = strlen(x);
         int n = strlen(y);
    
         for(int i = 1; i <= m; i++)
           for(int j = 1; j <= n; j++){
                 if(x[i-1] == y[j-1])
                       c[i][j] = c[i-1][j-1] + 1;
                 else
                       c[i][j] = max(c[i][j-1], c[i-1][j]);
           }

    return c[m][n]; }
  • 相关阅读:
    几种常见的软件架构
    路由事件
    PathAnimation
    String、Brush、Color 相互转换
    Sql 使用备份还是使用脚本
    WPF 路由事件
    WPF之复杂形状控件
    WPF之鼠标滑动切换图片
    WPF之基于路径的动画
    WPF之自定义控件
  • 原文地址:https://www.cnblogs.com/ShaneZhang/p/3971848.html
Copyright © 2011-2022 走看看