2个字符串中的行进字符序列

时间:2018-12-24 16:14:57

标签: c#

我必须编写搜索算法,例如,我必须将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);

1 个答案:

答案 0 :(得分:3)

解决方案:

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 ) ); 
    } 
}