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. iphone/ipad/iOS on Linux Debian7/ubuntu12.04/linuxmint13/ubuntu14.04 compiling from source

    The packages we need for ubuntu12.04 and its derived destros are: libimobiledevices, libplist, libus ...

  2. win7 安装 sql2000

    win7 安装:http://wenku.baidu.com/link?url=xNcfrMaMzX0KgBcjpMaySRaKITM2Op73ZI8sOX49zgl-GWPGB3vqye9gZA_c ...

  3. [置顶] ZK(The leading enterprise Ajax framework)入门指南

    1. Why ZK JavaEE领域从来就不缺少Framework尤其是Web Framework,光是比较流行的就有:SpringMVC.Struts2.JSF系列…… 其它不怎么流行的.小众的.非 ...

  4. 【解惑】剖析float型的内存存储和精度丢失问题

    问题提出:12.0f-11.9f=0.10000038,"减不尽"为什么? 现在我们就详细剖析一下浮点型运算为什么会造成精度丢失? 1.小数的二进制表示问题 首先我们要搞清楚下面两 ...

  5. 结构-行为-样式-requireJs实现图片轮播插件

    最近工作需要,就自己写了一个图片轮播插件,不过想到要集成到框架中,于是又用RequireJs改了一遍. 主要文件: style.css jquery-1.11.1.min.js require.js ...

  6. 通俗理解kalman filter原理

    [哲学思想]即使我们对真相(真值)一无所知,我们任然可以通过研究事物规律,历史信息,当前观测而能尽可能靠近真相(真值). [线性预测模型]温度的变化是线性规律的,已知房间温度真值每小时上升1度左右(用 ...

  7. [ios2] CABasicAnimation【转】

    caanimation 整理了解  http://geeklu.com/2012/09/animation-in-ios/ 几个可以用来实现热门APP应用PATH中menu效果的几个方法 +(CABa ...

  8. Android自定义控件系列(一)—Button七十二变

    转载请注明出处:http://www.cnblogs.com/landptf/p/6290791.html 忙了一段时间,终于有时间整理整理之前所用到的一些知识,分享给大家,希望给同学们有些帮助,同时 ...

  9. IONIC之简易购物车

    HTML <div ng-app="app"> <div class="l-header"> <div class="l ...

  10. RHEL账号总结一:账号的分类

    账号是一种用来记录单个用户或者多个用户的数据.RHEL中每一个合法的用户都必须拥有账号,才能使用RHEL. 在RHEL上的账号可以分为两类: 用户账号:用来存储单一用户的数据,你也可以使用一个用户账号 ...