一种方法可以是索引您要搜索的字符串的每个字符。
“蛇”会给出:
- s > {0}
- e > {1, 4}
- r > {2}
- p > {3}
- n > {5}
- t > {6}
因此,对于您在此字符串中搜索的每个单词,请在字典中查找其第一个和最后一个字符。
如果找到了,则需要查看相应的索引以找到可以匹配字符串长度的对。
一旦找到,您可以进行完整的字符串比较,但仅限于这种情况。
代码可以是这样的(c#):
static void Main( string[] args )
{
List<string> words = new List<string>() { "se", "s", "pen", "oo", "st" };
List<int> scores = new List<int>( words.Select( w => 0 ) );
List<string> strings = new List<string>() { "serpent", "lose", "last", "stools", "sat" };
foreach ( var s in strings )
{
var indexes = MakeIndexes( s );
for ( int i = 0 ; i < words.Count ; i++ )
{
scores[i] += Score( words[i], s, indexes );
}
}
}
static int Score( string word, string s, Dictionary<char, List<int>> indexes )
{
int firstPos = 0, lastPos = word.Length - 1;
char first = word[firstPos];
char last = word[lastPos];
List<int> firstIndexes;
if ( indexes.TryGetValue( first, out firstIndexes ) )
{
if ( firstPos == lastPos )
return 1;
else
{
List<int> lastIndexes;
if ( indexes.TryGetValue( last, out lastIndexes ) )
{
int fiPos = 0, liPos = 0;
while ( fiPos < firstIndexes.Count && liPos < lastIndexes.Count )
{
int fi = firstIndexes[fiPos], li = lastIndexes[liPos];
int len = li - fi;
if ( len < lastPos )
liPos++;
else if ( len == lastPos )
{
if ( FullCompare( word, s, fi ) )
return 1;
fiPos++;
liPos++;
}
else
fiPos++;
}
}
}
}
return 0;
}
static bool FullCompare( string word, string s, int from )
{
for ( int i = 0 ; i < word.Length ; i++ )
if ( word[i] != s[i + from] )
return false;
return true;
}
static Dictionary<char, List<int>> MakeIndexes( string s )
{
Dictionary<char, List<int>> result = new Dictionary<char, List<int>>();
for ( int i = 0 ; i < s.Length ; i++ )
{
char c = s[i];
List<int> indexes;
if ( result.TryGetValue( c, out indexes ) == false )
{
indexes = new List<int>();
result.Add( c, indexes );
}
indexes.Add( i );
}
return result;
}