-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
47 lines (44 loc) · 1.24 KB
/
Solution.cs
File metadata and controls
47 lines (44 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class Solution
{
public int LongestCommonSubsequence(string text1, string text2)
{
int[,] dp = new int[text1.Length + 1, text2.Length + 1];
for (int i = 1; i <= text1.Length; i++)
{
for (int j = 1; j <= text2.Length; j++)
{
if (text1[i - 1] == text2[j - 1])
{
dp[i, j] = dp[i - 1, j - 1] + 1;
}
else
{
dp[i, j] = Math.Max(dp[i - 1, j], dp[i, j - 1]);
}
}
}
return dp[text1.Length, text2.Length];
}
public int LongestCommonSubsequence_1D(string text1, string text2)
{
int[] dp = new int[text2.Length + 1];
for (int i = 1; i <= text1.Length; i++)
{
int prev = 0;
for (int j = 1; j <= text2.Length; j++)
{
int temp = dp[j];
if (text1[i - 1] == text2[j - 1])
{
dp[j] = prev + 1;
}
else
{
dp[j] = Math.Max(dp[j], dp[j - 1]);
}
prev = temp;
}
}
return dp[text2.Length];
}
}