首页 > 解决方案 > 2个字符串中的行进字符序列

问题描述

我必须编写搜索算法,例如我必须str="giorgi"str2="grigol". 我试图找到最长匹配的字符序列,以便字符的顺序是相同的,我应该得到的字符串是"grg"......我得到的这个 c# 代码"grig"

int k=0;
        string s="";
        string str = "giorgi";
        string str2 = "grigol";
        for(int i=0;i<str.Length;i++)
        {
            for (int j = k; j < str2.Length; j++)
            {
                if (str[i] == str2[j])
                {
                    s += str2[k];
                    k++;
                    goto endofloop;
                }

            }
        endofloop:;
        }

        Console.WriteLine(s);

标签: c#

解决方案


解决方案:

using System; 
class GFG 
{ 

    /* Returns length of LCS for X[0..m-1], Y[0..n-1] */
    static int lcs( char[] X, char[] Y, int m, int n ) 
    { 
        int [,]L = new int[m+1,n+1]; 

        /* Following steps build L[m+1][n+1]  
        in bottom up fashion. Note 
        that L[i][j] contains length of  
        LCS of X[0..i-1] and Y[0..j-1] */
        for (int i = 0; i <= m; i++) 
        { 
            for (int j = 0; j <= n; j++) 
            { 
                if (i == 0 || j == 0) 
                    L[i, j] = 0; 
                else if (X[i - 1] == Y[j - 1]) 
                    L[i, j] = L[i - 1, j - 1] + 1; 
                else
                    L[i, j] = GFG.max(L[i - 1, j], L[i, j - 1]); 
            } 
        } 
        return L[m, n]; 
    }

    static int max(int a, int b) 
    { 
        return (a > b)? a : b; 
    } 
} 

现在测试它的程序:

    public static void Main() 
    { 

        String s1 = "giorgi"; 
        String s2 = "grigol"; 

        char[] X=s1.ToCharArray(); 
        char[] Y=s2.ToCharArray(); 
        int m = X.Length; 
        int n = Y.Length; 

        Console.Write("Length of LCS is" + " " +lcs( X, Y, m, n ) ); 
    } 
} 

推荐阅读