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 ...
随机推荐
- Newtonsoft.Json 时区差解决方法
在使用Newtonsoft.Json时会遇到这样的问题,数据库存的值跟接收到反序列的值差了8个小时.这时,只要在反序列化时设置一下就可以了. JsonConvert.DeserializeObject ...
- Arduino 各种模块篇 震动模块 vibrator
vibrator is a good thing. it has multi-funtionality . :) Now the vibrator we choose is the one whic ...
- 为什么MD5不能解密
MD5加密原理是散列算法,也称之为hash算法. 具体的算法很多种,我也不是很懂,写得太专业了,我们只能理解一些简单的.简单才能让人记得住. 举例说明,10除以3余数是1,4除以3的余数也是1,反过来 ...
- javascript操作正则表达式对象的方法总结
//正则表达式对象 /* var s = 'good good study day day up '; var r, re; re = new RegExp('study',"g" ...
- Acoustic Echo Cancellation (AEC) 回音消除技术探索
回声产生的原因: 本地产生的音频信息通过网络传输到远端, 远端音频信号通过反射再由远端麦克采集到远端系统,再通过IP网络传输本地,本地播放后,在由本地麦克采集到,这就构成了类似闭环正反 ...
- HDU 1880 字符串hash 入门题
Problem Description 哈利波特在魔法学校的必修课之一就是学习魔咒.据说魔法世界有100000种不同的魔咒,哈利很难全部记住,但是为了对抗强敌,他必须在危急时刻能够调用任何一个需要的魔 ...
- 在code first结构下的生成的数据迁移文件,upadate-database失败
程序控制台出现 already exist Table "xxx",是由于项目中的Migrations(迁移文件)与连接的mysql数据库里迁移记录表里的数量及名称不一致.
- 【C#】Creating/Querying/Modifying the .mdb databases
As for databases, there are quit many kinds such as foxpro, mysql, sqlserver, etc. But when we need ...
- vim编辑器的简单使用
写这篇文章是因为在更新我的一篇博客 Git的其他用法 的时候,里面的修改已经提交的commit说明这一部分需要用到vim. 在使用git config --global --edit或者git reb ...
- java基础练习 3
import java.util.Scanner; public class Third { /*计算字符串中子串出现的次数 (5 分数)*/ public static void main(Stri ...