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 ...
随机推荐
- Kendo UI开发教程(9): Kendo UI Validator 概述
Kendo UI Validator 支持了客户端校验的便捷方法,它基于HTML 5 的表单校验功能,支持很多内置的校验规则,同时也提供了自定义规则的便捷方法. 完整的Kendo UI 的Valida ...
- java.io.IOException: Unable to open sync connection!的解决方案
在学习Android的时候,经常是使用手机调试程序,很方便,后来 在使用手机调试程序的时候出现了 [2012-03-08 11:27:43 - Tea_marsListActivity] ------ ...
- iOS抽奖程序
iOS抽奖程序 代码下载地址: http://vdisk.weibo.com/s/HKehU http://pan.baidu.com/share/link?shareid=893330225& ...
- Android开发(21)--有关Spinner控件的使用说明
下拉列表 Spinner,Spinner是一个每次只能选择所有项的一个项的控件.它的项来自于与之相关联的适配器中. Spinner的使用,可以极大提高用户的体验性.当需要用户选择的时候,可以提供一个下 ...
- kubernetes入门之快速部署
角色说明 这里主要有三个角色,分别部署不同的服务. 角色 服务 etcd etcd master kube-apiserver/kube-scheduler/kube-controller node ...
- Android 布局详解
Android 布局详解 1.重用布局 当一个布局文件被多处使用时,最好<include>标签来重用布局. 例如:workspace_screen.xml的布局文件,在另一个布局文件中被重 ...
- 利刃 MVVMLight 2:Model、View、ViewModel结构以及全局视图模型注入器的说明
上一篇我们已经介绍了如何使用NuGet把MVVMLight应用到我们的WPF项目中.这篇我们来了解下一个基本的MVVMLight框架所必须的结构和运行模式. MVVMLight安装之后,我们 ...
- MySQL闪回原理与实战
本文将介绍闪回原理,给出笔者的实战经验,并对现存的闪回工具作比较. DBA或开发人员,有时会误删或者误更新数据,如果是线上环境并且影响较大,就需要能快速回滚.传统恢复方法是利用备份重搭实例,再应用去除 ...
- Maven配置插件跳过测试代码的编译和运行
Maven配置插件跳过测试代码的编译和运行: <!-- 编译插件 --> <plugin> <groupId>org.apache.maven.plugins< ...
- 【转】关于JVM CPU资源占用过高的问题排查
http://my.oschina.net/shipley/blog/520062 一.背景: 先执行一个java程序里面开了两个线程分别都在while循环做打印操作. ? 1 # java -cp ...