804. Unique Morse Code Words(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/82704321

题目:

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.

解释:
需要用到字典(或者是类似于字典的操作啦)和集合(set),因为问的是独一无二的个数。
python代码:

class Solution:
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        morse=[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        _set=set()
        for word in words:
            morseCode=''
            for letter in word:
                morseCode+=morse[ord(letter)-ord('a')]
            _set.add(morseCode)
        return len(_set)

c++代码:

#include <vector>
#include <unordered_set>
#include <set>
using namespace std;
class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        
        vector<string> d={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        set<string> s;
        for (auto word:words)
        {
            string code;
            for(auto c:word)
            {
                code+=d[c-'a'];
            }
            s.insert(code);
        }
        return s.size();

    }
};

总结:
c++需要用到<vector><set>或者<unordered_set>,需要学会使用者几个容器。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/82704321