1. 程式人生 > >leetcode-804-Unique Morse Code Words

leetcode-804-Unique Morse Code Words

vector example PE put OS uem lower mis IE

題目描述:

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, "cab" 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.

要完成的函數:

int uniqueMorseRepresentations(vector<string>& words)

說明:

1、這道題給定一個vector,裏面存放著多個字符串,字符串中的每一個字母都對應一個摩爾斯碼。要求把給定的字符串翻譯成摩爾斯碼,最後返回有多少種不同的摩爾斯碼。

2、明白題意,這道題也沒有什麽快速的方法來實現,就直接暴力解法做吧。

外層循環,取出每個字符串。

內層循環,取出字符串中的逐個字母,一一對照著翻譯成摩爾斯碼,最終結果存儲在新定義的string中,把string一一加入到set中。

最後返回set的個數就可以了。

代碼如下:

    int uniqueMorseRepresentations(vector<string>& words) 
    {
        set<string>res;//存儲翻譯之後的摩爾斯碼
        vector<string>morse={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        int s1=words.size(),s2;
        string t;//臨時變量
        for(int i=0;i<s1;i++)//逐一取出字符串
        {
            s2=words[i].size();
            t="";
            for(int j=0;j<s2;j++)//逐一取出字母
                t+=morse[words[i][j]-‘a‘];//翻譯成摩爾斯碼
            res.insert(t);//存儲到set中
        }
        return res.size();
    }

上述代碼邏輯清晰,實測6ms,beats 99.70% of cpp submissions。

leetcode-804-Unique Morse Code Words