JavaScript 算法来匹配字典中的单词

发布于 2024-10-28 04:04:33 字数 195 浏览 1 评论 0原文

我有一个包含几千个单词的数组。我的网页上有一个输入字段,允许用户输入几个字母,然后单击搜索。当用户点击搜索时,应用程序应该在字典中查找,看看可以用提供的字母组成哪些单词。每个字母只能使用一次(就像拼字游戏一样)。

是否已经有一个搜索库可以做这样的事情?如果没有必要,我不想重新发明轮子。如果没有,是否有人有高性能解决方案的想法。我想这之前已经被做过数百万次了。

I have an array that contains a few thousand words. I have an input field on my webpage that allows a user to enter in a couple of letters, and then hit search. When the user hits search, the application should look in the dictionary and see what words can be formed off of the supplied letters. Each letter can be used only once ( like in scrabble ).

Is there already a search library for doing something like this? I don't want to reinvent the wheel if not necessary. If not, does anyone have ideas for a high performance solution. I'd imagine this has been done millions of times before.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

聆听风音 2024-11-04 04:04:33

jQuery 名人 John Resig 也一直在思考这个问题:

http://ejohn。 org/blog/dictionary-lookups-in-javascript/

John Resig of jQuery fame has been thinking about this problem as well:

http://ejohn.org/blog/dictionary-lookups-in-javascript/

你的呼吸 2024-11-04 04:04:33

Steve Hanov 也写了一些关于此的内容:

http://stevehanov.ca/blog/index.php ?id=120

Steve Hanov wrote something about this too:

http://stevehanov.ca/blog/index.php?id=120

慕烟庭风 2024-11-04 04:04:33

您需要做的是将单词数组转换为哈希表,其中键是每个单词的字母排序。例如:

['car', 'shoe', 'train']
=> {'acr': ['car'],
     'ehos': ['shoe'],
     'ainrt': ['train']}

然后你获取用户的字母,对它们进行排序,然后使用排序后的字母作为键进行哈希表(任何字典实现都可以,但哈希表在这种情况下是最有效的)查找。与您的键对应的列表是您可以用这些字母执行的单词列表。这样做的优点是时间复杂度为 O(n) = 1。

What you need to do is convert the array of words in a hashtable where the key is each word's letters sorted. Ex:

['car', 'shoe', 'train']
=> {'acr': ['car'],
     'ehos': ['shoe'],
     'ainrt': ['train']}

Then you take the user's letters, you sort them, and you do a hashtable (any dictionary impl would do, but hashtables are most efficient in this case) lookup using the sorted letters as key. The list corresponding to your key is the list of words you can do with those letters. This has the advantage of having a time complexity of O(n) = 1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文