Which datatype and methods should I use?

会有一股神秘感。 提交于 2019-12-02 19:55:51

问题


I am trying to write a kind of simple search engine. I have a determined number of main subjects that are associated with specific keywords. The aim is to recognize the main subject from an input partial keyword. I am thinking of using a : Dictionary<string, List<string>>. I'll have to search in this dictionary and find, e.g., all keywords beginning with a 3 characters string and their main subject which is associated.

Is my solution the best one ? And how can I efficiently look through those data without having to check manually every List, string by string.

Let my know if I'am not clear.


回答1:


You're looking for Trie data structure, it is the recommended way of doing starts with search. Here is a blog post talking about it. You can find the source here.

Here's how use the above implementation, code from the above article.

//Create trie
Trie < string > trie = new Trie < string > ();

//Add some key-value pairs to the trie
trie.Put("James", "112");
trie.Put("Jake", "222");
trie.Put("Fred", "326");

//Search the trie
trie.Matcher.NextMatch('J'); //Prefix thus far: "J"
trie.Matcher.GetPrefixMatches(); //[112, 222]
trie.Matcher.IsExactMatch(); //false
trie.Matcher.NextMatch('a');
trie.Matcher.NextMatch('m'); //Prefix thus far: "Jam"
trie.Matcher.GetPrefixMatches(); //[112]
trie.Matcher.NextMatch('e');
trie.Matcher.NextMatch('s'); //Prefix thus far: "James"
trie.Matcher.IsExactMatch(); //true
trie.Matcher.GetExactMatch(); //112

//Remove a string-value pair
trie.Remove("James");


来源:https://stackoverflow.com/questions/23910101/which-datatype-and-methods-should-i-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!