c# - 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);
解决方案
解决方案:
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 ) );
}
}
推荐阅读
- kubernetes - 如何编辑自定义资源仅删除一个终结器
- python - 如何将 Python 中的 reportlab 生成的 PDF 转换为 HTML
- azure-devops - Terraform Azure Devops 创建固件规则
- asp.net - ASP.NET 会话超时无效,除非 cookieless=true
- opengl - 有没有更好/更有效的方法来捕获 Linux 中的复合 X 窗口?
- c - 与 C 中的指针相关
- angular - 得到“错误 TS2304:找不到名称 'id'。” 当试图测试“ngx-diagram”示例时
- python-3.x - Python3 - 为每个循环迭代重置日志文件名
- fabricjs - FabricJS:有没有办法使对象在剪辑蒙版之外无法选择?
- php - 如何通过条件转换数据从数据库中提取数据?