Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2f6bb18

Browse files
ADD Longest-Common-Subsequence problem #68
1 parent 6f59802 commit 2f6bb18

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

‎Medium/longest-common-subsequence.cs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using System;
2+
3+
public class Solution
4+
{
5+
private static int[,] _FillMatrix(string text1, string text2)
6+
{
7+
int[,] matrix = new int[text1.Length + 1, text2.Length + 1];
8+
9+
for (int i = text1.Length - 1; i >= 0; i--)
10+
{
11+
for (int j = text2.Length - 1; j >= 0; j--)
12+
{
13+
if (text1[i] == text2[j])
14+
{
15+
matrix[i, j] = 1 + matrix[i + 1, j + 1];
16+
}
17+
else
18+
{
19+
matrix[i, j] = Math.Max(matrix[i, j + 1], matrix[i + 1, j]);
20+
}
21+
}
22+
}
23+
24+
return matrix;
25+
}
26+
27+
public static int LongestCommonSubsequence(string text1, string text2)
28+
{
29+
if (string.IsNullOrWhiteSpace(text1) || string.IsNullOrWhiteSpace(text2))
30+
{
31+
return 0;
32+
}
33+
34+
if (text1 == text2)
35+
{
36+
return text1.Length;
37+
}
38+
39+
int[,] matrix = _FillMatrix(text1, text2);
40+
41+
return matrix[0, 0];
42+
}
43+
44+
public static void Main(string[] args)
45+
{
46+
Console.WriteLine(LongestCommonSubsequence("zxabcdezy", "yzabcdezx"));
47+
48+
Console.ReadKey();
49+
}
50+
}
51+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /