Functional programming:
public class Solution {
readonly string[] morseCodes = new[] {
".-","-...","-.-.","-..",".",
"..-.","--.","....","..",".---",
"-.-",".-..","--","-.","---",
".--.","--.-",".-.","...","-",
"..-","...-",".--","-..-","-.--","--.."
};
public int UniqueMorseRepresentations(string[] words) =>
words.Select(word =>
word.Skip(1).Aggregate(
morseCodes[word[0] - 'a'].ToString(),
(txMorse, current) => txMorse + morseCodes[current - 'a']
)
).Distinct().Count();
}
Imperative programming:
public class Solution {
public int UniqueMorseRepresentations(string[] words) {
var morseCodes = new[] {
".-","-...","-.-.","-..",".",
"..-.","--.","....","..",".---",
"-.-",".-..","--","-.","---",
".--.","--.-",".-.","...","-",
"..-","...-",".--","-..-","-.--","--.."
};
var distinctMorses = new HashSet();
var buildMorse = new StringBuilder();
foreach (var word in words) {
foreach (var c in word) {
buildMorse.Append(morseCodes[c - 'a']);
}
var txMorse = buildMorse.ToString();
buildMorse.Clear();
if (!distinctMorses.Contains(txMorse)) {
distinctMorses.Add(txMorse);
}
}
return distinctMorses.Count;
}
}
Source:
https://leetcode.com/problems/unique-morse-code-words/
No comments:
Post a Comment