问题描述
假设我有两个字符串string1
和string2
。
var string1 = "images of canadian geese goslings";
var string2 = "Canadian geese with goslings pictures to choose from,with no signup needed";
我需要找到string1
中匹配的string2
的最大子字符串。
此处最大的子字符串为"canadian geese"
,与string2
中的字符串匹配。
如何找到它?我尝试将string1
分解为char[]
,然后找到单词,然后合并匹配的单词,但这没有达到我的目标。
解决方法
经典循环方法-结果包括鹅"canadian geese "
后的空格
var string1 = "images of canadian geese goslings";
var string2 = "Canadian geese with goslings pictures to choose from,with no signup needed";
string result = "";
for (int i = 0; i < string1.Length; i++)
{
for (int j = 0; j < string1.Length - i; j++)
{
//add .Trim() here if you want to ignore space characters
string searchpattern = string1.Substring(i,j);
if (string2.IndexOf(searchpattern,StringComparison.OrdinalIgnoreCase) > -1 && searchpattern.Length > result.Length)
{
result = searchpattern;
}
}
}
https://dotnetfiddle.net/q3rHjI
旁注:
canadian
和Canadian
不相等,因此如果要搜索不区分大小写的内容,则必须使用StringComparison.OrdinalIgnoreCase
看看下面的代码https://dotnetfiddle.net/aPyw3o
public class Program {
static IEnumerable<string> substrings(string s,int length) {
for (int i = 0 ; i + length <= s.Length; i++) {
var ss = s.Substring(i,length);
if (!(ss.StartsWith(" ") || ss.EndsWith(" ")))
yield return ss;
}
}
public static void Main()
{
int count = 0;
var string1 = "images of canadian geese goslings";
var string2 = "Canadian geese with goslings pictures to choose from,with no signup needed";
string result = null;
for (int i = string1.Length; i>0 && string.IsNullOrEmpty(result); i--) {
foreach (string s in substrings(string1,i)) {
count++;
if (string2.IndexOf(s,StringComparison.CurrentCultureIgnoreCase) >= 0) {
result = s;
break;
}
}
}
if (string.IsNullOrEmpty(result))
Console.WriteLine("no common substrings found");
else
Console.WriteLine("'" + result + "'");
Console.WriteLine(count);
}
}
substrings
方法返回字符串s
的所有子字符串,其长度为length
(有关yield
的信息,请参见文档https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield)我们跳过以空格开头或结尾的子字符串,因为我们不希望空格使子字符串的长度超过实际长度)
外部循环遍历子字符串的所有可能的长度值,从最长(即string1.Length
)到最短(即1
)。然后,对于每个找到的长度为i
的子字符串,检查它是否也是string2
的子字符串。在这种情况下,我们可以停止,因为不再有公共子字符串,因为我们在先前的迭代中检查了所有更长的子字符串。但是,当然还有其他一些常见的子字符串,其长度为i
我将使用span / readonlymemory再添加一个,这样您就可以避免分配当前答案创建的所有字符串。请注意,我没有对开始空间或结束空间进行任何检查,因为这似乎不是问题的必要条件。这样做确实进行了不区分大小写的搜索,如果您不希望通过使用内置的indexof并删除不区分大小写的比较,可以使其效率更高。
static void Main(string[] _)
{
var string1 = "images of canadian geese goslings";
var string2 = "Canadian geese with goslings pictures to choose from,with no signup needed";
var longest = FindLongestMatchingSubstring(string1,string2);
Console.WriteLine(longest);
}
static string FindLongestMatchingSubstring(string lhs,string rhs)
{
var left = lhs.AsMemory();
var right = rhs.AsMemory();
ReadOnlyMemory<char> longest = ReadOnlyMemory<char>.Empty;
for (int i = 0; i < left.Length; ++i)
{
foreach (var block in FindMatchingSubSpans(left,i,right))
{
if (block.Length > longest.Length)
longest = block;
}
}
if (longest.IsEmpty)
return string.Empty;
return longest.ToString();
}
static IEnumerable<ReadOnlyMemory<char>> FindMatchingSubSpans(ReadOnlyMemory<char> source,int pos,ReadOnlyMemory<char> matchFrom)
{
int lastMatch = 0;
for (int i = pos; i < source.Length; ++i)
{
var ch = source.Span[i];
int match = IndexOfChar(matchFrom,lastMatch,ch);
if (-1 != match)
{
lastMatch = match + 1;
int end = i;
while (++end < source.Length && ++match < matchFrom.Length)
{
char lhs = source.Span[end];
char rhs = matchFrom.Span[match];
if (lhs != rhs && lhs != (char.IsUpper(rhs) ? char.ToLower(rhs) : char.ToUpper(rhs)))
{
break;
}
}
yield return source.Slice(i,end - i);
}
}
}
static int IndexOfChar(ReadOnlyMemory<char> source,char ch)
{
char alt = char.IsUpper(ch) ? char.ToLower(ch) : char.ToUpper(ch);
for (int i = pos; i < source.Length; ++i)
{
char m = source.Span[i];
if (m == ch || m == alt)
return i;
}
return -1;
}