我建议使用的字典。使用字符串作为键和字符串列表作为值。对要搜索的字符串进行标记,并将整个字符串添加到您的字典中,以便为每个标记添加一次。 (Youn可以使用split方法来标记字符串,使用空格作为分隔符。)之后,无论何时您需要查找,都会标记搜索字符串并查找字典中的每个标记。
因此,如果您已经添加下列字符串:FOO,巴兹,酒吧,等等,富吧,富巴兹
你的字典里条目:
富:FOO,FOO酒吧,富巴兹 巴兹:巴兹,富巴兹 酒吧:酒吧,酒吧FOO等等 :等等
如果您再搜索“富巴”,
你的输出是下FOO存储和酒吧像条目的工会所以: “富巴”:= FOO,酒吧
富:FOO,FOO酒吧,富巴兹 工会 酒吧:酒吧,FOO酒吧
捐赠:FOO,FOO酒吧,富巴兹,酒吧
编辑:我刚刚注意到,你只需要完整或部分匹配,即foo巴兹是不可接受的。简单的解决方案是后处理结果 - 将搜索字符串和目标字符串的长度限制为较短字符串的长度,然后将截短字符串与未修改字符串进行比较。只接受那些相同的东西。
编辑:所以事实证明,foo baz确实是一场比赛。忽略上述段落(第一次编辑)。 见(C#)代码如下:
class DictionarySearch
{
private Dictionary<string, List<string>> dict;
public DictionarySearch()
{
dict = new Dictionary<string, List<string>>();
}
/// <summary>
/// Add a string e.g. foo bar to the dictionary
/// </summary>
/// <param name="s">string to be added</param>
public void addString(string s)
{
//tokenize string
string[] words = s.Split(new char[] { ' ' });
//add each token to the dictionary as a key with the matching value being s
foreach (string w in words)
{
if (dict.ContainsKey(w))
{
dict[w].Add(s);
}
else
{
dict.Add(w, new List<string>());
dict[w].Add(s);
}
}
}
/// <summary>
/// Find all strings which match at least one token
/// </summary>
/// <param name="s">string of tokens (words) to be matched</param>
/// <returns>List of strings matching at least one word</returns>
public IList<string> getMatches(string s)
{
//split search string into words
string[] words = s.Split(new char[] { ' ' });
List<string> output = new List<string>();
//retrieve from dictionary list of strings matching each word.
foreach (string w in words)
{
if (dict.ContainsKey(w))
{
output.AddRange(dict[w]);
}
else
{
continue;
}
}
return output;
}
}
鉴于与每串Q字和n的唯一字,并用升字的搜索串m串的辞典的时间复杂性是如下:
填充数据结构:O(q m T [dictionary-insert])。需要对每个单词执行插入操作
查找字符串:O(l * T [dictionary-find])。搜索字符串中的每个单词的字典查找。
实际成本取决于您的字典实施。基于哈希表的字典会导致插入和查找的O(1)成本。基于二叉树的字典会导致插入和查找的O(lg n)成本。
是串英文单词,也可以包含任何字符?他们是否区分大小写? – Adamski 2009-09-15 17:04:25
@Adamski他们是英语单词,不区分大小写;然而,他们是非常专业的词汇,就像你在字典中找不到的东西。 – 2009-09-15 17:08:45
如果字典中包含“foob”,如果我搜索“foo”,或者您只关注精确匹配,是否会返回? – Adamski 2009-09-15 17:16:22