pull/1/head
Ogoun 5 years ago
parent 3ca25d345b
commit 68699d2056

@ -0,0 +1,47 @@
using Xunit;
using ZeroLevel.Semantic;
namespace ZeroLevel.UnitTests
{
public class LCSTest
{
[Fact]
public void LCSTest1()
{
// Arrange
var s_base = "abcdefghijklmnopqrstuvwxyz";
var s1 = "klmnO";
var s2 = "";
string s3 = null;
// Act
var st11 = LongestCommonSubstring.LCS(s_base, s1);
var st12 = LongestCommonSubstring.LCS(s1, s_base);
var st13 = LongestCommonSubstring.LCSIgnoreCase(s_base, s1);
var st14 = LongestCommonSubstring.LCSIgnoreCase(s1, s_base);
var st21 = LongestCommonSubstring.LCS(s_base, s2);
var st22 = LongestCommonSubstring.LCS(s2, s_base);
var st31 = LongestCommonSubstring.LCS(s_base, s3);
var st32 = LongestCommonSubstring.LCS(s3, s_base);
//Assert
Assert.Equal("klmn", st11);
Assert.Equal("klmn", st12);
Assert.Equal(s1, st13, ignoreCase: true);
Assert.Equal(s1, st14, ignoreCase: true);
Assert.Equal(string.Empty, st21);
Assert.Equal(string.Empty, st22);
Assert.Equal(string.Empty, st31);
Assert.Equal(string.Empty, st32);
}
}
}

@ -0,0 +1,47 @@
namespace ZeroLevel.Semantic
{
public static class LongestCommonSubstring
{
public static string LCS(string s1, string s2)
{
if (s1 == null || s2 == null || s1.Length == 0 || s2.Length == 0) return string.Empty;
var a = new int[s1.Length + 1, s2.Length + 1];
int u = 0, v = 0;
for (var i = 0; i < s1.Length; i++)
for (var j = 0; j < s2.Length; j++)
if (s1[i] == s2[j])
{
a[i + 1, j + 1] = a[i, j] + 1;
if (a[i + 1, j + 1] > a[u, v])
{
u = i + 1;
v = j + 1;
}
}
return s1.Substring(u - a[u, v], a[u, v]);
}
public static string LCSIgnoreCase(string s1, string s2)
{
if (s1 == null || s2 == null || s1.Length == 0 || s2.Length == 0) return string.Empty;
var a = new int[s1.Length + 1, s2.Length + 1];
int u = 0, v = 0;
for (var i = 0; i < s1.Length; i++)
for (var j = 0; j < s2.Length; j++)
if (char.ToUpperInvariant(s1[i]) == char.ToUpperInvariant(s2[j]))
{
a[i + 1, j + 1] = a[i, j] + 1;
if (a[i + 1, j + 1] > a[u, v])
{
u = i + 1;
v = j + 1;
}
}
return s1.Substring(u - a[u, v], a[u, v]);
}
}
}
Loading…
Cancel
Save

Powered by TurnKey Linux.