Solution of Morse

For every word we will do the following:
Let's say we are at word W(i). We compute its morse encoding and using a mapping from morseEncoding to number of apparitions, we will keep track of how many times a morse encoding appeared in the dictionary.
So at step i we will increment the number of apparitions of the morse encoding we obtained from W(i) where i=1...n. In order the manage this mapping we can use a hash table that maps strings to integers. We can then compute the answer by iterating through the values of the hash.
If there are no collisions, we print -1.
#include <iostream>
#include <stdio.h>
#include <unordered_map>
#include <vector>

using namespace std;

int main() {
    int n, ans = 0;
    vector <string> d;
    unordered_map<char, string> repr;
    unordered_map<string, int> cnt;
    for(int i = 0; i < 26; ++ i) {
        char ch;
        string code;
        cin >> ch >> code;
        repr[ch] = code;
    }
    cin >> n;
    for(int i = 0; i < n; ++ i) {
        string word;
        cin >> word;
        string morse = "";
        for(auto ch : word)
            morse = morse + repr[ch];
        ans = max(ans, ++ cnt[morse]);
    }
    if(ans == 1)
        cout << -1 << '\n';
    else
        cout << ans << '\n';
    return 0;
}
Questions?

Sponsors Gold