題目
國際摩爾斯密碼定義一種标準編碼方式,将每個字母對應于一個由一系列點和短線組成的字元串, 比如: "a" 對應 ".-", "b" 對應 "-...", "c" 對應 "-.-.", 等等。
為了友善,所有26個英文字母對應摩爾斯密碼表如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
給定一個單詞清單,每個單詞可以寫成每個字母對應摩爾斯密碼的組合。例如,"cab" 可以寫成 "-.-.-....-",(即 "-.-." + "-..." + ".-"字元串的結合)。我們将這樣一個連接配接過程稱作單詞翻譯。
傳回我們可以獲得所有詞不同單詞翻譯的數量。
例如:
輸入: words = ["gin", "zen", "gig", "msg"]
輸出: 2
解釋:
各單詞翻譯如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
共有 2 種不同翻譯, "--...-." 和 "--...--.".
注意:
- 單詞清單words 的長度不會超過 100。
- 每個單詞 words[i]的長度範圍為 [1, 12]。
- 每個單詞 words[i]隻包含小寫字母。
解答
先上代碼再解釋。
class Solution(object):
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
m = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
w = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
d = dict(zip(w,m))
temp = set()
for index in words:
b = []
for i in index:
b.append(d[i])
s = ''.join(b)
temp.add(s)
return len(temp)
首先通過 zip 方法構造一個字典,目的是為了讓字母和摩爾斯密碼一一對應,然後周遊傳入的單詞,第二層循環周遊單詞的字母
再把字母對應的摩爾斯密碼傳入清單,拼接成字元串傳入set中,計算長度即可。
再來改進一下代碼。
class Solution(object):
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
m = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
w = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
d = dict(zip(w,m))
res = []
for index in words:
s = ''
for i in index:
s = s + d.get(i)
res.append(s)
return len(set(res))
基本上一樣,相對來說更好了解一點。