International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
'a'
maps to".-"
,'b'
maps to"-..."
,'c'
maps to"-.-."
, and so on.
For convenience, the full table for the 26
letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Given an array of strings words
where each word can be written as a concatenation of the Morse code of each letter.
- For example,
"cab"
can be written as"-.-..--..."
, which is the concatenation of"-.-."
,".-"
, and"-..."
. We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have
LeetCode Problem - 804
class Solution {
public int uniqueMorseRepresentations(String[] words) {
// Initialize a map to store the Morse code representation for each letter
Map<Character, String> mp = new HashMap<>();
// Array of Morse code representations corresponding to each letter from 'a' to 'z'
String[] morseCodes = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
"..-","...-",".--","-..-","-.--","--.."};
// Populate the map with letters 'a' to 'z' and their corresponding Morse code representations
char charValue = 'a';
for(String morseCode : morseCodes) {
mp.put(charValue, morseCode);
charValue++;
}
// List to store unique Morse code transformations
List<String> al = new ArrayList<>();
// Loop through each word in the input array
for(String word : words) {
StringBuilder sb = new StringBuilder(); // StringBuilder to construct the Morse code representation of the word
// Loop through each character in the word
for(int i = 0; i < word.length(); i++) {
// Get the Morse code for the current character and append it to the StringBuilder
String currentMorseCodeValue = mp.get(word.charAt(i));
sb.append(currentMorseCodeValue);
}
// If the Morse code representation is not already in the list, add it to the list
if(!al.contains(sb.toString())) {
al.add(sb.toString());
}
}
// Return the number of unique Morse code transformations
return al.size();
}
}