题目:
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
例如:
输入: words = ["gin", "zen", "gig", "msg"]
输出: 2
解释:
各单词翻译如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
共有 2 种不同翻译, "--...-." 和 "--...--.".
注意:
单词列表words 的长度不会超过 100。
每个单词 words[i]的长度范围为 [1, 12]。
每个单词 words[i]只包含小写字母。
这是我写的方法,很简单,就是存入哈希表
然后求出4个字符串,添加到集合,如果重复,就不添加,直接返回不重复的结果就ok了!
public static int UniqueMorseRepresentations(string[] words)
{
List<string> res = new List<string>();
var map = new Dictionary<char, string>();
HashSet<string> result = new HashSet<string>();
map.Add('a', ".-");
map.Add('b', "-...");
map.Add('c', "-.-.");
map.Add('d', "-..");
map.Add('e', ".");
map.Add('f', "..-.");
map.Add('g', "--.");
map.Add('h', "....");
map.Add('i', "..");
map.Add('j', ".---");
map.Add('k', "-.-");
map.Add('l', ".-..");
map.Add('m', "--");
map.Add('n', "-.");
map.Add('o', "---");
map.Add('p', ".--.");
map.Add('q', "--.-");
map.Add('r', ".-.");
map.Add('s', "...");
map.Add('t', "-");
map.Add('u', "..-");
map.Add('v', "...-");
map.Add('w', ".--");
map.Add('x', "-..-");
map.Add('y', "-.--");
map.Add('z', "--..");
foreach (var item in words)
{
string bbk = "";
for (int i = 0; i < item.Length; i++)
{
if (map.ContainsKey(item[i]))
{
bbk += map[item[i]];
}
}
//if(集合中包含了就不添加,最后返回)
if(!res.Contains(bbk))
res.Add(bbk);
}
return res.Count();
}
分享一个可以学习lamda的方法:
static string[] morse = new string[] { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
public static int UniqueMorseRepresentations(string[] words)
{
string ToMorse(char c) => morse[c - 'a'];
string ToMorseWord(string s) => string.Join("", s.Select(ToMorse));
return words.Select(ToMorseWord).Distinct().Count();
}

本文介绍了一种算法,用于计算给定单词列表中,不同摩尔斯电码翻译的总数。通过将每个字母转换为其对应的摩尔斯电码,再将单词内的电码连接起来,最终统计不重复的翻译数量。文章提供了实现代码示例。
463

被折叠的 条评论
为什么被折叠?



