Unique Morse Code Words
阿新 • • 發佈:2019-02-10
enc 根據 intern .com english leet case hab different
Algorithm
【leetcode】Unique Morse Code Words
https://leetcode.com/problems/unique-morse-code-words/
1)problem
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: [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word. Return 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 "--...--.". Note: The length of words will be at most 100. Each words[i] will have length in range [1, 12]. words[i] will only consist of lowercase letters.
2)answer
將26個因為字母映射為摩斯電碼,然後根據每組字母每個字符對應的摩斯電碼組合起來。至於那個簡寫是為什麽可以那麽寫,沒搞清楚。【"cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-").】
3)solution
#include "pch.h" #include <stdio.h> #include <string> #include <vector> #include <unordered_set> using std::string; using std::vector; using std::unordered_set; class Solution { public: int uniqueMorseRepresentations(vector<string>& words) { vector<string> morse_code = { ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.." }; // vector<string> store; unordered_set<string> result_val; int count = 0; for (auto str: words) { string tmp; for (auto ch: str) { //-'a'是找到輸入字的索引。例如,'a' - 'a'為0.所以'a'對應於morse_code中的第一個元素。 tmp += morse_code[(int)ch - (int)('a')]; } result_val.insert(tmp); } return result_val.size(); } }; int main() { vector<string> words; words.push_back("cba"); // 使用內容 Solution nSolution; nSolution.uniqueMorseRepresentations(words); }
Unique Morse Code Words