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. Web前端Require.js

    前言 前段时间粗略的扫过一次require.js,当时没怎么在意,结果昨天看到index里面的代码就傻了,完全不知道从哪开始看啦,所以require与backbone的学习还要加紧才行. 由于前端所占 ...

  2. POJ 1013 小水题 暴力模拟

    Counterfeit Dollar Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 35774   Accepted: 11 ...

  3. CF 327E(Axis Walking-状态压缩Dp-lowbit的使用)

    E. Axis Walking time limit per test 3 seconds memory limit per test 512 megabytes input standard inp ...

  4. install cuda5 on ubuntu12.04

    1. sudo apt-get install libglapi-mesa 2. sudo apt-get install freeglut3-dev build-essential libx11-d ...

  5. windows下练习linux shell

    <---开始学习linux---记录一下---路漫漫其修远兮---加油吧---萌萌达> 使用软件:Cygwin  下载地址(免安装版):链接: http://pan.baidu.com/s ...

  6. Wget 命令详解

    Wget主要用于下载文件,在安装软件时会经常用到,以下对wget做简单说明. 1.下载单个文件:wget http://www.baidu.com.命令会直接在当前目录下载一个index.html的文 ...

  7. Ionic2系列——在Ionic2中使用高德地图

    之前讲过了如何在Ionic2中使用第三方库,因为第三方库必须针对TypeScript提供相应的声明文件——即d.ts文件,才能被TypeScript正确识别并编译.好在大多数的第三方库已经有了定义文件 ...

  8. python绝技 — 使用PyGeoIP关联IP地址和物理位置

    准备工作 要关联IP与物理位置,我们需要有一个包含这样对应关系的数据库. 我们可以使用开源数据库GeoLiteCity,它能够较为准确地把IP地址与所在城市关联起来 下载地址:http://dev.m ...

  9. Linux上传与下载(sz-rz)

    linux使用rz和sz命令上传和下载文件! sz命令发送文件到本地: # sz filename rz命令本地上传文件到服务器: # rz 执行该命令后,在弹出框中选择要上传的文件即可. 说明:打开 ...

  10. [转]解决VS2008 开发Windows Mobile 项目生成速度慢的问题

    最近用VS2008开发Windows Mobile程序,使用C#..NET Compact Framework,发现项目生成速度比较慢.用VS2008打开项目后,开始一段时间生成速度还能忍受,时间一长 ...