[Swift]LeetCode804. 惟一摩爾斯密碼詞 | Unique Morse Code Words

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-okajlywk-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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.git

For convenience, the full table for the 26 letters of the English alphabet is given below:github

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

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.app

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.

國際摩爾斯密碼定義一種標準編碼方式,將每一個字母對應於一個由一系列點和短線組成的字符串, 好比: "a" 對應 ".-""b" 對應 "-...""c" 對應 "-.-.", 等等。spa

爲了方便,全部26個英文字母對應摩爾斯密碼錶以下:翻譯

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

給定一個單詞列表,每一個單詞能夠寫成每一個字母對應摩爾斯密碼的組合。例如,"cab" 能夠寫成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的結合)。咱們將這樣一個鏈接過程稱做單詞翻譯。code

返回咱們能夠得到全部詞不一樣單詞翻譯的數量。orm

例如:
輸入: words = ["gin", "zen", "gig", "msg"]
輸出: 2
解釋: 
各單詞翻譯以下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

共有 2 種不一樣翻譯, "--...-." 和 "--...--.". 

注意:

  • 單詞列表words 的長度不會超過 100
  • 每一個單詞 words[i]的長度範圍爲 [1, 12]
  • 每一個單詞 words[i]只包含小寫字母。

Runtime: 16 ms
Memory Usage: 20.2 MB
 1 class Solution {
 2     func uniqueMorseRepresentations(_ words: [String]) -> Int {
 3         let array = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
 4         return Set<String>(words.map { (word) -> String in
 5             let aWord = word.uppercased()
 6             var result = ""
 7             aWord.unicodeScalars.forEach({ (s) in
 8                 result += array[Int(s.value) - 65]
 9             })
10             return result
11         }).count
12     }
13 }

Runtime: 16 ms
Memory Usage: 19.9 MB
 1 class Solution {
 2     func uniqueMorseRepresentations(_ words: [String]) -> Int {
 3         var morse:[String] = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
 4         var s:Set<String> = Set<String>()
 5         for word in words
 6         {
 7             var t:String = String()
 8             for c in word
 9             {
10                 t += morse[c.ascii - 97]
11             }
12             s.insert(t)
13         }
14         return s.count
15     }
16 }
17 
18 //Character擴展 
19 extension Character  
20 {  
21   //Character轉ASCII整數值(定義小寫爲整數值)
22    var ascii: Int {
23        get {
24            return Int(self.unicodeScalars.first?.value ?? 0)
25        }       
26     }
27 }

24ms

 1 class Solution {
 2     func uniqueMorseRepresentations(_ words: [String]) -> Int {
 3         func transform(_ position: UInt32) -> String? {
 4             let morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
 5             let offset = "a".unicodeScalars.first!.value
 6             return morse[Int(position - offset)]
 7         }
 8         var result = Set<String>()
 9         for word in words {
10             let morseCode = word.unicodeScalars.compactMap { transform($0.value) }.joined()
11             result.update(with: morseCode)
12         }
13         return result.count
14     }
15 }

24ms

 1 class Solution {
 2     func uniqueMorseRepresentations(_ words: [String]) -> Int {
 3         var morse : [String] = Array(repeating: "", count: 97)
 4         morse.append(contentsOf: [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."])        
 5         
 6         var wordsSet : Set<String> = []
 7         var morseWord : String = "'"
 8         for word in words {
 9             morseWord = "'"
10             for w in word.unicodeScalars {
11                 morseWord.append(contentsOf: morse[Int(w.value)])
12             }
13             wordsSet.update(with: morseWord)
14         }
15         return wordsSet.count
16     }
17 }

 40ms

 1 class Solution {
 2     func uniqueMorseRepresentations(_ words: [String]) -> Int {
 3 
 4         let morseCodeArray = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
 5         let alphabets = "abcdefghijklmnopqrstuvwxyz"
 6         
 7         var morseSet: Set<String> = []
 8         
 9         for word in words {
10             var morseWord: String = ""
11             
12             for character in word {
13                 
14                 var order = 0
15                 var counter = 0
16                 
17                 for alphabet in alphabets {
18                     
19                     if character == alphabet {
20                         counter = order
21                     }
22                     order += 1
23                 }
24                 morseWord += morseCodeArray[counter]
25             }
26             morseSet.insert(morseWord)
27         }
28         return morseSet.count
29     }
30 }

36ms

 1 class Solution {
 2         private let passwordTable: [Character : String] = [
 3         "a" : ".-",
 4         "b" : "-...",
 5         "c" : "-.-.",
 6         "d" : "-..",
 7         "e" : ".",
 8         "f" : "..-.",
 9         "g" : "--.",
10         "h" : "....",
11         "i" : "..",
12         "j" : ".---",
13         "k" : "-.-",
14         "l" : ".-..",
15         "m" : "--",
16         "n" : "-.",
17         "o" : "---",
18         "p" : ".--.",
19         "q" : "--.-",
20         "r" : ".-.",
21         "s" : "...",
22         "t" : "-",
23         "u" : "..-",
24         "v" : "...-",
25         "w" : ".--",
26         "x" : "-..-",
27         "y" : "-.--",
28         "z" : "--..",
29         ]
30     
31     func uniqueMorseRepresentations(_ words: [String]) -> Int {
32         return Set(words.map {
33             $0.map({
34                 passwordTable[$0]!
35             }).reduce("", {
36                 $0 + $1
37             })
38         }).count
39     }
40 }

40ms

 1 class Solution {
 2     func uniqueMorseRepresentations(_ words: [String]) -> Int {
 3         // 字母表莫爾斯密碼字典
 4         var alphabet = Dictionary<String,String> () 
 5         let charAry = Array("abcdefghijklmnopqrstuvwxyz")
 6         let morseAry = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
 7         var res = Array<String>()
 8         var resList = Array<String>()
 9         
10         for (index,value) in charAry.enumerated() {
11             // String(value):char轉string 映射字母表莫爾斯密碼成字典
12             alphabet[String(value)] = morseAry[index] 
13         }
14         // 遍歷 ["gin", "zen", "gig", "msg"]
15         for (_,value) in words.enumerated() { 
16             var tmp = ""
17             // 遍歷 "gin"
18             for (_,value1) in String(value).enumerated() { 
19                 tmp.append(alphabet[String(value1)]!)
20             }
21             res.append(tmp) // "gin" => "--...-."
22         }
23         // 去重
24         for (_,value) in res.enumerated() { 
25             if !resList.contains(value) {
26                 resList.append(value)
27             }
28         }
29         
30         return resList.count
31     }
32 }

48ms

 1 class Solution {
 2     func uniqueMorseRepresentations(_ words: [String]) -> Int {        
 3         guard words.count > 1 else {
 4             return words.count
 5         }
 6 
 7         var transformationMap:[String: Bool] = [String: Bool]()
 8         var moorseDict:[Character: String] = 
 9             ["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":"--.."]
10         
11 
12         for var word in words {
13             var moorseCode = ""
14             for var letter in word {
15                 if let moorse = moorseDict[letter] {
16                     moorseCode += moorse
17                 }
18             }
19             transformationMap[moorseCode] = true
20         }
21         
22         return transformationMap.keys.count
23     }
24 }
相關文章
相關標籤/搜索