Little Puzzlers–List All Anagrams in a Word
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的更多相关文章
- [LeetCode]题解(python):049-Groups Anagrams
题目来源 https://leetcode.com/problems/anagrams/ Given an array of strings, group anagrams together. For ...
- HDU ACM 1515 Anagrams by Stack
Anagrams by Stack Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- JavaScript 44 Puzzlers
http://mp.weixin.qq.com/s?__biz=MzAxODE2MjM1MA==&mid=2651550987&idx=1&sn=f7a84b59de14d0b ...
- [leetcode]Anagrams @ Python
原题地址:https://oj.leetcode.com/problems/anagrams/ 题意: Given an array of strings, return all groups of ...
- 【Acm】算法之美—Anagrams by Stack
题目概述:Anagrams by Stack How can anagrams result from sequences of stack operations? There are two seq ...
- 44 道 JavaScript 难题(JavaScript Puzzlers!)
JavaScript Puzzlers原文 1. ["1", "2", "3"].map(parseInt) 答案:[1, NaN, NaN ...
- Anagrams leetcode java
题目: Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...
- Anagrams by Stack(深度优先搜索)
ZOJ Problem Set - 1004 Anagrams by Stack Time Limit: 2 Seconds Memory Limit: 65536 KB How can a ...
- Leetcode: Anagrams(颠倒字母而成的字)
题目 Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...
随机推荐
- C#制作高仿360安全卫士窗体2
C#制作高仿360安全卫士窗体 继上次C#制作高仿360安全卫士窗体<一>发布之后响应还不错,我的博客放肆雷特也来了不少的新朋友,在这里先谢谢大家的支持!我自己也反复看了一下觉得对不起大家 ...
- DataSet、DataTable、DataRow 复制
DataSet.DataTable.DataRow 复制 DataSet 对象是支持 ADO.NET的断开式.分布式数据方案的核心对象 ,用途非常广泛.我们很多时候需要使用其中的数据,比如取得一个Da ...
- JAVA多线程经典问题 -- 生产者 消费者
工作2年多来一直也没有计划写自己的技术博客,最近辞职在家翻看<thingking in JAVA>,偶尔看到了生产者与消费者的一个经典的多线程同步问题.本人在工作中很少使用到多线程以及高并 ...
- Javascript内存泄漏
Javascript内存泄漏 原文:http://point.davidglasser.net/2013/06/27/surprising-javascript-memory-leak.html 本周 ...
- php memcached+Mysql(主从)
/* index.php 程序入口,用来构造sql(如查询,更新) config.php 配置参数(memcache,mysql) init.php 封装memcached操作(memca ...
- Linux设备驱动开发详解-Note(5)---Linux 内核及内核编程(1)
Linux 内核及内核编程(1) 成于坚持,败于止步 Linux 2.6 内核的特点 Linux 2.6 相对于 Linux 2.4 有相当大的改进,主要体现在如下几个方面. 1.新的调度器 2.6 ...
- svn的使用详细说明
转载请指明:杨凯专属频道 1.在电脑的任意位置创建一个版本库文件夹 最好是全英文的目录 例如 在c:\svn下面创建一个 2.打开此文件,在这里右键 找--TortoiseSVN--->Crea ...
- 使用JDK中的安全包对数据进行加解密
本文以使用DES对称加密算法为例使用jdk对数据进行加密解密. 首先需要了解Provider类,它是jdk引入的密码服务提供者概念,实现了Java安全性的一部分或者全部.Provider 可能实现的服 ...
- Nodejs --我自己的学习笔记
对于Nodejs,相信客官并不陌生,网上却已众说纷纭,有人说是一个平台,有人说是服务器JavaScript,有人说一个框架… 之前亦有过研究,多怀可远观而不可亵玩也.高效率,I/O操作,异步编程,以及 ...
- SVG基础以及使用Javascript DOM操作SVG
SVG 不依赖分辨率 支持事件处理器 最适合带有大型渲染区域的应用程序(比如谷歌地图) 复杂度高会减慢渲染速度(任何过度使用 DOM 的应用都不快) 不适合游戏应用 Canvas 依赖分辨率 不支持事 ...