hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

Unique Morse Code Words / Morse Code To English


  • Approach:

    1. Map each character to its corresponding morse code.

    2. For the LeetCode problem, derive morse code for each character of each given word.

      • Push them into a HashSet.

      • Return the HashSet size.

    3. For the CodingNinja problem, derive the word from the given morse code.

      • Return the word


  • Time and Space Complexity:

      • Time Complexity: O(N)

      • Space Complexity: O(N), where N = number of characters in total


Code [C++] [LeetCode]

class Solution {

public:

string code[26] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};

unordered_set<string>myset;

int uniqueMorseRepresentations(vector<string>& words) {

for(int i=0; i<words.size(); i++){

string trans = "";

for(int j=0; j<words[i].size(); j++){

trans += code[words[i][j] - 'a'];

}

myset.insert(trans);

}

return myset.size();

}

};

Code [C++] [CodingNinja]

#include <bits/stdc++.h>

string morseToEnglish(string morsecode)

{

string alphabet[36] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----." };

stringstream ss(morsecode);

string ans = "";

while(ss >> morsecode){

for(int i=0; i<26; i++){

if(morsecode == alphabet[i]){

ans += ('a' + i);

break;

}

}

for(int i=26; i<36; i++){

if(morsecode == alphabet[i]){

ans += (i - 26) + 48;

break;

}

}

}

return ans;

}