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 ...
随机推荐
- notes/Set up development environment on windows
恰好前几天买了个新笔记本, 15存 sony vaio, 终于从mac回到了windows. 不过作为(曾经的)*nix追随者, 没有bash真是寸步难行, 幸好windows8.x有了super s ...
- 三种工厂模式的分析以及C++实现
三种工厂模式的分析以及C++实现 以下是我自己学习设计模式的思考总结. 简单工厂模式 简单工厂模式是工厂模式中最简单的一种,他可以用比较简单的方式隐藏创建对象的细节,一般只需要告诉工厂类所需要的类型, ...
- .NET依托CLR进行的内存的管理
看了http://www.cnblogs.com/liulun/p/3145351.html 不错,补习下相关技术.. 正文: .NET依托CLR进行的内存的管理 有了CLR 基本不需要担心.net ...
- Linux上传与下载(sz-rz)
linux使用rz和sz命令上传和下载文件! sz命令发送文件到本地: # sz filename rz命令本地上传文件到服务器: # rz 执行该命令后,在弹出框中选择要上传的文件即可. 说明:打开 ...
- VR电影这一新概念在中国电影道路上的探索
在12月的一个下午,Kevin Geiger正在进行关于VR中的故事讲述的一次再普通不过的演讲.地点是北京电影学院里一个围的水泄不通的场馆,他鼓励大家都来参与电影制作,无论是导演.演员还是电影行业的任 ...
- Python map多线程
import os import PIL from multiprocessing import Pool from PIL import Image SIZE = (75,75) SAVE_DIRE ...
- JavaScript - 平稳退化
JavaScript使用window对象的open()方法来创建新的浏览器窗口.这个方法有三个参数:window.open(url,name,features)这三个参数都是可选的.1.第一个参数是想 ...
- DrawingCombiner——CAD图纸批量合并软件
DrawingCombiner是一款CAD图纸批量合并软件,可以批量合并多个dwg或dxf文件为单个dwg文件,并可以设置合并后的排列方式. 此程序附属MagicTable(可到依云官网下载:http ...
- Linux下gcc,g++,gdb,scon部分用法笔记
1 Ubuntu下编译安装GCC-4.1.2 拷贝gcc-4.1.2.tar.bz2(我下载的压缩文件)到/usr/local/src 解压 新生成的gcc-4.1.2这个目录被称为源目录,用${sr ...
- 文档在线预览开源实现方案三:OpenOffice + PDFRenderer + js
之前的方案无法很好地解决异构平台及不同浏览器的兼容性问题,如方案一需要客户端浏览器支持flash而移动端浏览器无法支持这点,虽然移动端浏览器支持方案二,但是一些老版本的IE浏览器无法支持,例如IE8就 ...