今天選的這題一樣是選#Easy、答對率也高的題目
題目內容:
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 "--...--.".
我想到的做法是先用replace()函式把每個英文字母都取代成對應的摩斯代碼,在用set()留下不同的字串
所以想到的程式碼架構大概長這樣:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
new_words = []
for i in words:
for j in i:
i = i.replace(j,morse[ord(j)-97])
new_words.append(i)
return len(set(new_words))
這邊有查到參考1用ord的方式可以找出字母的ASCII十進位值,因為a~z是97~122,是連續的一串,所以拿到ASCII之後減去開頭的97就好。
submit後結果如下: