leetcode problem solution --804. The only Morse code word

International standards define a Morse code coding, each letter corresponding to a character string consisting of a series of dots and dashes, such as: "a" corresponding to ".-", "b" corresponding to "-..." , "c" corresponding to "-.-.", and the like.

For convenience, all 26 letters of the alphabet Morse code correspondence table is as follows:


[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]



Given a list of words, each word can be written for each letter of the Morse code combinations. For example, "CAB" can be written "-.-.. - ..." (i.e., "-.-." + "-..." + ".-" binding string). We refer to such a connection process is called word translation.

Return we can get a number of different word translation of all the words.


E.g:

输入: words = ["gin", "zen", "gig", "msg"]

Output: 2

Explanation:

Each word translation as follows:

"gin" -> "--...-."

"zen" -> "--...-."

"gig" -> "--...--."

"msg" -> "--...--."

There are two different translation, "--...-." And "--...--.."


note:

    The word list length will not exceed 100 words.

    Each word words [i] of length in the range [1, 12].

    Each word words [i] contains only lowercase letters.



The idea is simple problem-solving traversal


C++

class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        vector<string> hashMap = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        unordered_set<string> strResSet;//利用集合的元素唯一性去重,记录所有单词翻译的结果
        for (auto &word : words)
        {
            string tempStr;
            for (auto &ch :word) 
};
        }
            strResSet ××× ERT (tempStr);.
            }
                tempStr hashMap '= + [CH -' A '];
                // letter-by-word translation
            {
        return (int) strResSet.size ();


Python:

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        codeList = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        trans = set()
        for word in words:
            trans.add(''.join(map(lambda c: codeList[ord(c)-97], word)))
        return len(trans)



Guess you like

Origin blog.51cto.com/12876518/2409771