The Solution

A major hint is in the fact we are given a dictionary.  Because we are given this dictionary we can prep it in any way we like when the program starts, and then the processing of any word input becomes simple.  Most dictionaries will easily fit within memory of modern computing hardware, so this should not be a major concern.

So, having the dictionary, we have all possible valid word anagrams already.  The only trick is how to get from the input to these words.

So let’s think, “what do all anagrams have in common?”  For example, the word “post” has “pots”, “stop”, “tops”, etc.  It may seem obvious, but all anagrams have the same letters.  Thus, if we can hash or organize these letters in a consistent way, we can store all anagrams under the same key.  In this way, we can apply the same hash/organization to the input word, immediately get the list of anagrams, and simply exclude the input word from the anagram list.

The simplest way to do this would simply be to sort the letters, this is a fairly simple operation in C#:

var key = string.Concat(word.ToLower().OrderBy(c => c));

That would turn “post”, “pots”, etc. all into: “opst” which we can use as our key for our lookup.  Now, how to store them, you could download your own multidictionary, or create a Dictionary<string, List<string>>,but really C# already has one for you called a Lookup.  The Lookup stores a key to multiple values.

So first, let’s write a simple DAO for reading in our words from a file:

public class WordFileDao : IWordDao
{
public string FileName { get; private set; } public WordFileDao(string fileName)
{
FileName = fileName;
} public IEnumerable<string> RetrieveWords()
{
// make sure to remove any accidental space and normalize to lower case
return File.ReadLines(FileName).Select(l => l.Trim().ToLower());
}
}

Then, we can create an anagram finder to create the lookup on construction, and then find words on demand:

public class AnagramFinder
{
private readonly ILookup<string, string> _anagramLookup; public AnagramFinder(IWordDao dao)
{
// construct the lookup at initialization using the
// dictionary words with the sorted letters as the key
_anagramLookup = dao.RetrieveWords().ToLookup(
k => string.Concat(k.OrderBy(c => c)));
} public IList<string> FindAnagrams(string word)
{
// at lookup time, sort the input word as the key,
// and return all words (minus the input word) in the sequence
string input = word.ToLower();
string key = string.Concat(input.OrderBy(c => c)); return _anagramLookup[key].Where(w => w != input).ToList();
}
}

Notice the ToLookup() extension method (in System.Linq), this method creates an instance of Lookupfrom any IEnumerable<T> if you provide it a key generator and a value generator.  For the key generator, I’m returning the word in sorted, lowercase (for consistency).  For the value, I’m just lower-casing the word (again, for consistency).  This effectively creates the “dictionary of key to list of values” that, when you query using the “[…]” operator, will return an IEnumerable<T> of the values, or empty sequence if the key was not found.

And that’s it!  We have our anagram word finder which can lookup words quickly with only the cost of sorting the letters in a word, which is much less expensive (processing-wise) than attempting all permutations of the letters in a word.

Quote From:

Solution to Little Puzzlers–“List All Anagrams in a Word”

Little Puzzlers–List All Anagrams in a Word的更多相关文章

  1. [LeetCode]题解(python):049-Groups Anagrams

    题目来源 https://leetcode.com/problems/anagrams/ Given an array of strings, group anagrams together. For ...

  2. HDU ACM 1515 Anagrams by Stack

    Anagrams by Stack Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others ...

  3. JavaScript 44 Puzzlers

    http://mp.weixin.qq.com/s?__biz=MzAxODE2MjM1MA==&mid=2651550987&idx=1&sn=f7a84b59de14d0b ...

  4. [leetcode]Anagrams @ Python

    原题地址:https://oj.leetcode.com/problems/anagrams/ 题意: Given an array of strings, return all groups of ...

  5. 【Acm】算法之美—Anagrams by Stack

    题目概述:Anagrams by Stack How can anagrams result from sequences of stack operations? There are two seq ...

  6. 44 道 JavaScript 难题(JavaScript Puzzlers!)

    JavaScript Puzzlers原文 1. ["1", "2", "3"].map(parseInt) 答案:[1, NaN, NaN ...

  7. Anagrams leetcode java

    题目: Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...

  8. Anagrams by Stack(深度优先搜索)

    ZOJ Problem Set - 1004 Anagrams by Stack Time Limit: 2 Seconds      Memory Limit: 65536 KB How can a ...

  9. Leetcode: Anagrams(颠倒字母而成的字)

    题目 Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...

随机推荐

  1. wget ( download the whole page from the website )

    ---恢复内容开始--- wget -m -e robots=off -U "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1 ...

  2. [Thinkbayes]贝叶斯思维读书笔记-1-贝叶斯定理

    使用贝叶斯定理,目前来看最重要的一点在于假设.就是未知事件已知化,同时也要注意假设的全程性,不能从中开始新的假设,这种假设往往是不全面的. 我自己找到的假设的方法有两种,一种是命名,一种是时序.全程性 ...

  3. ajaxfileupload 实现多文件上传

    官网下载ajaxfileupload.js: 修改源码: jQuery.extend({ createUploadIframe: function(id, uri) { //create frame ...

  4. .NET基础——基本概念

    1.   .NET.C#(sharp)和JAVA .net是一种多语言的平台,开发.net可以用多达几十种语言进行开发. C#(sharp)是一种编程语言,可开发基于.net平台的应用. Java既是 ...

  5. 【翻译】在Mac上使用VSCode创建你的第一个Asp.Net Core应用

    Setting Up Your Development Environment 设置你的开发环境 To setup your development machine download and inst ...

  6. JS 处理十六进制颜色渐变算法-输入颜色,输出渐变rgb数组

    html颜色有几种表示方式: 英文单词颜色值:background-color:Blue:十六进制颜色值:background-color:#FFFFFF:  RGB颜色值三元数字:backgroun ...

  7. appium+robotframework的简单实例

    在上篇文章中,我们搭建好了appium+robotframework的环境,这篇文章中主要是一个简单实例. 一.测试用例编写前提 1.模拟器(或手机)连接电脑 adb devices         ...

  8. 巧用weui.gallery(),点击图片后预览图片

    要在页面需要加载的JS文件: <script src="../js/libs/weui.min.js"></script> 可以去weui的文档中下载,这是 ...

  9. Ubuntu14.04安装wineqq国际版出现无法输入中文的解决方法

    执行命令:sudo vim /usr/bin/wine-qqintl 将"export LANG=zh_CN.utf8"改为"export LANG=en_US.utf8 ...

  10. webstrom30天免费试用期过后如何破解继续使用

    之前下了ws 直接就用了 也没有破解 30天过去了 老是提示你 神烦  网上找了一堆注册码什么的 终于发现一个良心网站 http://idea.qinxi1992.cn/ 步骤看下面的图