zoukankan      html  css  js  c++  java
  • 求两个字符串的相似度或子串

    View Code
    #include<IOSTREAM.H>
    #include <IOMANIP.H>
    #include <STRING.H>
    #include <STDLIB.H>
    //求两个字符串的最大公共子串
    //公共子串是指两个串中存在相同顺序的字符,但这些字符不必相邻
    /*int Length(int *array,char * A,int m,char *B,int n)
    {
        if (array[(strlen(B)+1)*m+n]<strlen(B))
            return array[(strlen(B)+1)*m+n];
        int temp;
        if (A[m-1]==B[n-1])
        {
            temp=1+Length(array,A,m-1,B,n-1);
            
        }
        else
        {
            int temp1=0,temp2=0;
            temp1=Length(array,A,m-1,B,n);
            temp2=Length(array,A,m,B,n-1);
            temp=(temp1>temp2)?temp1:temp2;
        }
        array[(strlen(B)+1)*m+n]=temp;
        return temp;
    }
    void main()
    {
        char B[]="BDCABA";
        char A[]="ABCBDAB";
        int *array=(int*)malloc((strlen(A)+1)*(strlen(B)+1)*sizeof(int));
        for (int i=0;i<strlen(A)+1;i++)
        {
            for (int j=0;j<strlen(B)+1;j++)
            {
                if(i==0) array[(strlen(B)+1)*i+j]=0;
                else if (j==0) array[(strlen(B)+1)*i+j]=0;
                else
                    array[(strlen(B)+1)*i+j]=strlen(A)<strlen(B)?strlen(A):strlen(B);
            }
        }
        cout<<Length(array,A,strlen(A),B,strlen(B))<<endl;
        for (i=0;i<strlen(A)+1;i++)
        {
            for (int j=0;j<strlen(B)+1;j++)
            {
                cout<<setw(3)<<array[(strlen(B)+1)*i+j];
            }
            cout<<endl;
        }
        free(array);
        cout<<endl;
    }*/
    //采用自底向上的方法
    void main()
    {
        char A[]="ACCGGTCGAGTGCGCGGAAGCCGGCCGAA";
        char B[]="GTCGTTCGGAATGCCGTTGCTCTGTAAA";
        int array[30][29];
        for (int i=0;i<30;i++)
            array[i][0]=0;
        for (int j=0;j<29;j++)
            array[0][j]=0;
        for (i=1;i<30;i++)
        {
            for (j=1;j<29;j++)
            {
                if (A[i-1]==B[j-1])
                {
                    array[i][j]=1+array[i-1][j-1];
                }else
                {
                    array[i][j]=array[i-1][j]>=array[i][j-1]?array[i-1][j]:array[i][j-1];
                }
            }
        }
        i=29;j=28;
        while(i&&j)
        {
            if(array[i][j]!=array[i-1][j]&&array[i][j]!=array[i][j-1])
            {
                cout<<A[i-1];
                i=i-1;j=j-1;
            }else if (array[i][j]==array[i-1][j])
            {
                i=i-1;
            }
            else
                j=j-1;
        }
        cout<<endl;
        cout<<array[29][28]<<endl;
    }
  • 相关阅读:
    剑指Offer47 不用加减乘除做加法
    剑指Offer46 求1+2+...+n
    剑指Offer45 约瑟夫环
    剑指Offer44 扑克牌的顺子
    剑指Offer43 n个骰子点数概率
    面试题分享
    初识python版本
    redis安装部署
    配置本地yum源
    闭包、装饰器
  • 原文地址:https://www.cnblogs.com/GoAhead/p/2748778.html
Copyright © 2011-2022 走看看