1. 程式人生 > 其它 >刷題-力扣-804. 唯一摩爾斯密碼詞

刷題-力扣-804. 唯一摩爾斯密碼詞

題目連結

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/unique-morse-code-words
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

題目描述

國際摩爾斯密碼定義一種標準編碼方式,將每個字母對應於一個由一系列點和短線組成的字串, 比如:

  • 'a' 對應 ".-" ,
  • 'b' 對應 "-..." ,
  • 'c' 對應 "-.-." ,以此類推。
    為了方便,所有 26 個英文字母的摩爾斯密碼錶如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

給你一個字串陣列 words ,每個單詞可以寫成每個字母對應摩爾斯密碼的組合。

例如,"cab" 可以寫成 "-.-..--..." ,(即 "-.-." + ".-" + "-..." 字串的結合)。我們將這樣一個連線過程稱作 單詞翻譯 。
對 words 中所有單詞進行單詞翻譯,返回不同 單詞翻譯 的數量。

示例 1:

輸入: words = ["gin", "zen", "gig", "msg"]
輸出: 2
解釋: 
各單詞翻譯如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

共有 2 種不同翻譯, "--...-." 和 "--...--.".

示例 2:

輸入:words = ["a"]
輸出:1

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 12
  • words[i] 由小寫英文字母組成

題目分析

  1. 根據題目描述,計算一組字串可以產生的摩爾斯密碼的組合數
  2. 遍歷字串陣列,生成摩爾斯密碼,再統計摩爾斯密碼的組合數

程式碼

const static std::string morseCode[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};

class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        std::unordered_set<std::string> morsePwd;
        for (std::string str : words) {
            std::string pwd = "";
            for (auto c : str) {
                pwd += morseCode[c - 'a'];
            }
            morsePwd.emplace(pwd);
        }
        return morsePwd.size();
    }
};