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

    公共子序列
    f[i][j]表示a[0,...,i-1] 和 b[0,...,j-1] 最长公共子序列的长度。

    
    import java.util.*;
    public class Main {
        static int solution(char[] a, char[] b) {
            int n = a.length, m = b.length;
            int[][] f = new int[n+1][m+1];
            for(int i=1; i <= n; i++) {
                for(int j=1; j <= m; j++) {
                    if(a[i-1] != b[j-1]) {
                        f[i][j] = Math.max(f[i-1][j], f[i][j-1]);
                    } else 
                        f[i][j] = f[i-1][j-1] + 1;
                }
            }
            //System.out.println(Arrays.deepToString(f));
            return f[n][m];
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            while(sc.hasNext()) {
                char[] a = sc.next().toLowerCase().toCharArray();
                char[] b = sc.next().toLowerCase().toCharArray();
                int res = solution(a,b);
                System.out.println(res);
            }
        }
    }
    

    公共子串
    f[i][j]表示以a[i-1] 和 b[j-1] 结尾的子串,最长公共子串的长度。

    import java.util.*;
    public class Main {
        static int solution(char[] a, char[] b) {
            int n = a.length, m = b.length;
            int[][] f = new int[n+1][m+1];
            for(int i=1; i <= n; i++) {
                for(int j=1; j <= m; j++) {
                    if(a[i-1] == b[j-1])
                        f[i][j] = f[i-1][j-1] + 1;
                }
            }
            //System.out.println(Arrays.deepToString(f));
            int res = 0;
            for(int i=0; i <= n; i++)
                for(int j=0; j <= m; j++)
                    res = Math.max(res, f[i][j]);
            return res;
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            while(sc.hasNext()) {
                char[] a = sc.next().toLowerCase().toCharArray();
                char[] b = sc.next().toLowerCase().toCharArray();
                int res = solution(a,b);
                System.out.println(res);
            }
        }
    }
    
  • 相关阅读:
    基于vue的可视化编辑器
    IOS系统兼容input keyup事件
    js滚动事件实现滚动触底加载
    移动端 input 输入框实现自带键盘“搜索“功能并修改X
    clipboard.js兼容ios
    js实现点击复制网页内容(基于clipboard.js)
    js实现点击复制网页内容(基于execCommand)
    knn 数字识别
    knn 算法 k个相近邻居
    sklearn 线性回归
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13257238.html
Copyright © 2011-2022 走看看