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:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Find the number of different transformations among all words we have.
Example:
Input: words = ["gin", "zen", "gig", "msg"] Output: 2 Explanation: The transformation of each word is: "gin" -> "--...-." "zen" -> "--...-." "gig" -> "--...--." "msg" -> "--...--." There are 2 different transformations, "--...-." and "--...--.".
Approach:
Java
import java.util.HashSet;
public class UniqueMorseRepresentations {
// define 1-26 char decode
static String arr[] = { ".-", "-...", "-.-.", "-..", ".",
"..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.." };
public static void main(String[] args) {
String words[] = { "gin", "zen", "gig", "msg" };
System.out.println(uniqueMorseRepresentations(words));
}
// method to find unique
public static int uniqueMorseRepresentations(String[] words) {
// create set for add unique string
HashSet<String> s = new HashSet<>();
// iterate till end of words
for (int i = 0; i < words.length; i++) {
StringBuffer sb = new StringBuffer();
String w = words[i];
// for each char
for (int j = 0; j < w.length(); j++) {
sb.append(arr[w.charAt(j) - 97]);
}
s.add(sb.toString());
}
return s.size();
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find the unique
//morse representation of all words
int uniqueMorseRepresentations(vector<string>& words) {
map<char,string> mp;
//unique morse code for each
//character
string arr[]={".-","-...","-.-.","-..",".",
"..-.","--.","....","..",".---","-.-",
".-..","--","-.","---",".--.","--.-",
".-.","...","-","..-","...-",".--",
"-..-","-.--","--.."};
set<string> st;
for(int i=0;i<26;i++)
mp[i+'a']=arr[i];
for(int i=0;i<words.size();i++)
{
string str="";
for(int j=0;j<words[i].size();j++)
str+=mp[words[i][j]];
st.insert(str);
}
return st.size();
}
int main()
{
vector<string> words = {"gin", "zen", "gig", "msg"};
int unique=uniqueMorseRepresentations(words);
cout<<unique<<"\n";
return 0;
}
No comments:
Post a Comment