我试图找出一种在大字符串中查找重复短语的有效方法。该字符串将包含由空格分隔的数百或数千个单词。我在下面包含了我目前正在使用的代码,但在查找重复短语方面效率很低。
public static string FindDuplicateSubstringFast(string s, string keyword, bool allowOverlap = true)
{
int matchPos = 0, maxLength = 0;
if (s.ToLower().Contains(keyword.ToLower()))
for (int shift = 1; shift < s.Length; shift++)
{
int matchCount = 0;
for (int i = 0; i < s.Length - shift; i++)
{
if (s[i] == s[i + shift])
{
matchCount++;
if (matchCount > maxLength)
{
maxLength = matchCount;
matchPos = i - matchCount + 1;
}
if (!allowOverlap && (matchCount == shift))
{
// …Run Code Online (Sandbox Code Playgroud)