[Swift]LeetCode748. 最短完整詞 | Shortest Completing Word

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

Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlategit

Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word.github

It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.微信

The license plate might have the same letter occurring multiple times. For example, given a licensePlate of "PP", the word "pair"does not complete the licensePlate, but the word "supper" does.ui

Example 1:spa

Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
Output: "steps"
Explanation: The smallest length word that contains the letters "S", "P", "S", and "T".
Note that the answer is not "step", because the letter "s" must occur in the word twice.
Also note that we ignored case for the purposes of comparing whether a letter exists in the word.

Example 2:code

Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
Output: "pest"
Explanation: There are 3 smallest length words that contains the letters "s".
We return the one that occurred first. 

Note:component

  1. licensePlate will be a string with length in range [1, 7].
  2. licensePlate will contain digits, spaces, or letters (uppercase or lowercase).
  3. words will have a length in the range [10, 1000].
  4. Every words[i] will consist of lowercase letters, and have length in range [1, 15].

若是單詞列表(words)中的一個單詞包含牌照(licensePlate)中全部的字母,那麼咱們稱之爲完整詞。在全部完整詞中,最短的單詞咱們稱之爲最短完整詞。htm

單詞在匹配牌照中的字母時不區分大小寫,好比牌照中的 "P" 依然能夠匹配單詞中的 "p" 字母。blog

咱們保證必定存在一個最短完整詞。當有多個單詞都符合最短完整詞的匹配條件時取單詞列表中最靠前的一個。

牌照中可能包含多個相同的字符,好比說:對於牌照 "PP",單詞 "pair" 沒法匹配,可是 "supper" 能夠匹配。

示例 1:

輸入:licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
輸出:"steps"
說明:最短完整詞應該包括 "s"、"p"、"s" 以及 "t"。對於 "step" 它只包含一個 "s" 因此它不符合條件。同時在匹配過程當中咱們忽略牌照中的大小寫。

示例 2:

輸入:licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
輸出:"pest"
說明:存在 3 個包含字母 "s" 且有着最短長度的完整詞,但咱們返回最早出現的完整詞。 

注意:

  1. 牌照(licensePlate)的長度在區域[1, 7]中。
  2. 牌照(licensePlate)將會包含數字、空格、或者字母(大寫和小寫)。
  3. 單詞列表(words)長度在區間 [10, 1000] 中。
  4. 每個單詞 words[i] 都是小寫,而且長度在區間 [1, 15] 中。

104ms

 1 class Solution {
 2     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3         var dict = [Character: Int]()
 4         for char in licensePlate {
 5             if (char >= "a" && char <= "z") || (char >= "A" && char <= "Z") {
 6                 let lowerCaseChar = char.toLowerCase()
 7                 if let value = dict[lowerCaseChar] {
 8                     dict[lowerCaseChar] = value + 1
 9                 } else {
10                     dict[lowerCaseChar] = 1
11                 }
12             }
13         }
14         var answer = ""
15         var count = 1001
16 
17         for word in words {
18             let wordCount = word.count
19             if wordCount >= count {
20                 continue
21             }
22             var wordDict = [Character: Int]()
23             for char in word {
24                 if let value = wordDict[char] {
25                     wordDict[char] = value + 1
26                 } else {
27                     wordDict[char] = 1
28                 }
29             }
30 
31             var completed = true
32             for key in dict.keys {
33                 if let value = wordDict[key] {
34                     if value < (dict[key]!) {
35                         completed = false
36                     }
37                 } else {
38                     completed = false
39                     break
40                 }
41             }
42             if completed, wordCount < count {
43                 answer = word
44                 count = answer.count
45             }
46         }
47         return answer
48     }
49 }
50 
51 extension Character {
52     static let upperToLowerDict: [Character: Character] = ["A": "a", "B": "b", "C": "c", "D": "d", "E": "e", "F": "f", "G": "g",
53                                                            "H": "h", "I": "i", "J": "j", "K": "k", "L": "l", "M": "m", "N": "n",
54                                                            "O": "o", "P": "p", "Q": "q", "R": "r", "S": "s", "T": "t", "U": "u",
55                                                            "V": "v", "W": "w", "X": "x", "Y": "y", "Z": "z"]
56     func toLowerCase() -> Character {
57         if self >= "a" && self <= "z" {
58             return self
59         } else {
60             return Character.upperToLowerDict[self]!
61         }
62     }
63 }

Runtime: 108 ms
Memory Usage: 20 MB
 1 class Solution {
 2     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3         var counter:[Int] = [Int](repeating:0,count:26)
 4         for c in licensePlate
 5         {
 6             if (c <= "z") && (c >= "a") {counter[c.ascii - 97] += 1}
 7             if (c <= "Z") && (c >= "A") {counter[c.ascii - 65] += 1}
 8         }
 9         var foundAns:Bool = false
10         var ans:String = String()
11         for s in words
12         {
13             var count:[Int] = [Int](repeating:0,count:26)
14             for c in s
15             {
16                 if (c <= "z") && (c >= "a") {count[c.ascii - 97] += 1}
17                 if (c <= "Z") && (c >= "A") {count[c.ascii - 65] += 1}
18             }
19             var found:Bool = true
20             for i in 0..<26
21             {
22                 if counter[i] > count[i]
23                 {
24                     found = false
25                     break
26                 }
27             }
28             if found
29             {
30                 if (!foundAns) || (ans.count > s.count)
31                 {
32                     ans = s
33                 }
34                 foundAns = true;
35             }
36         }
37        return ans
38     }
39 }
40 
41 //Character擴展
42 extension Character
43 {
44     //Character轉ASCII整數值(定義小寫爲整數值)
45     var ascii: Int {
46         get {
47             return Int(self.unicodeScalars.first?.value ?? 0)
48         }
49     }
50 }

120ms

 1 class Solution {
 2     private let set: Set<Character> = Set(Array("abcdefghijklmnopqrstuvwxyz"))
 3     
 4     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 5         let license = freq(licensePlate)
 6         var result: String? = nil
 7         
 8         for word in words {
 9             if let r = result, word.count >= r.count {
10                 continue
11             }
12             
13             let f = freq(word)
14             var valid = true
15             for (key, value) in license {
16                 let fv = f[key, default: 0]
17                 if fv < value {
18                     valid = false
19                     break
20                 }
21             }
22             
23             if valid {
24                 result = word
25             }
26         }
27         
28         return result ?? ""
29     }
30     
31     private func freq(_ str: String) -> [Character: Int] {
32         var dict = [Character: Int]()
33         
34         for char in Array(str.lowercased()) {
35             guard set.contains(char) else { continue }
36             dict[char] = dict[char, default: 0] + 1
37         }
38         
39         return dict
40     }
41 }

124ms

 1 class Solution {
 2     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3         // let letters = String(licensePlate.unicodeScalars.filter ({ CharacterSet.letters.contains($0) })).lowercased()
 4         let letters = licensePlate.components(separatedBy: CharacterSet.letters.inverted).joined(separator: "").lowercased()
 5                                                                                 // print(letters)
 6                                                                         
 7 
 8         var shortestAnswer = ""        
 9         
10         let lowers = words.map({ $0.lowercased() })
11                 
12         for word in lowers {
13             var test = letters
14 
15             for c in word {
16                 if let idx = test.index(of: c) {
17                     test.remove(at: idx)
18                     
19                     if test.count == 0 {
20                         break
21                     }
22                 } else {
23                     continue
24                 }                  
25             }
26                         
27             if test.count == 0 {
28                 if word.count < shortestAnswer.count {
29                     shortestAnswer = word
30                 }
31                 if shortestAnswer.count == 0 {
32                     shortestAnswer = word
33                 }
34             }
35             
36         }
37                 
38         return shortestAnswer
39     }
40 }

136ms

 1 class Solution {
 2     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3        // var words = words.sorted{ $0.count < $1.count }
 4         var licensePlate = licensePlate.lowercased()
 5         var total = 0
 6         var freq = [Character: Int]()
 7         for c in licensePlate {
 8             guard c >= "a", c <= "z" else { continue }
 9             freq[c, default: 0 ] += 1
10             total += 1
11         }
12         var res = ""
13         for s in words {
14             var cnt = total
15             var t = freq
16             for c in s {
17                 t[c, default: 0] -= 1
18                 if t[c]! >= 0 { cnt -= 1 }
19             }
20             if cnt == 0 && (res.isEmpty || res.count > s.count) {
21                 res = s
22             }
23         }
24         return res
25     }
26 }

144ms

 1 class Solution {
 2     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3         var licensePlateCounts = [Character: Int]()
 4 
 5         for char in licensePlate.lowercased() {
 6             if ("a"..."z").contains(char) {
 7                 licensePlateCounts[char, default: 0] += 1
 8             }
 9         }
10 
11 let sortedWords = words.enumerated().sorted {
12     if $0.element.count == $1.element.count {
13         return $0.offset < $1.offset
14     } else {
15         return $0.element.count < $1.element.count
16     }
17 }.map { $0.element }
18                 
19         for word in sortedWords {
20             var countsDict = licensePlateCounts
21             for char in word {
22                 if let count = countsDict[char] {
23                     if count > 1 {
24                         countsDict[char] = count - 1
25                     } else {
26                         countsDict[char] = nil
27                     }
28                 }
29 
30                 if countsDict.isEmpty {
31                     return word
32                 }
33             }
34         }
35         return "impossible"
36     }
37 }

152ms

 1 class Solution {
 2 func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3     var dp = [Character:Int]()
 4     for item in licensePlate.lowercased(){
 5         if item >= Character("a") && item <= Character("z"){
 6             dp[item, default:0] += 1
 7         }
 8     }
 9     var result = "1"
10     for item in words {
11         var temp = [Character:Int]()
12         for subitem in item.lowercased(){
13             if subitem >= Character("a") && subitem <= Character("z"){
14                 temp[subitem, default:0] += 1
15             }
16         }
17         var flag = true
18         for (key,value) in dp{
19             if value > temp[key, default:0]{
20                 flag = false
21                 break
22             }
23         }
24         if flag {
25             if result == "1"{
26                 result = item
27             }else{
28                 result = item.count >= result.count ? result : item
29             }
30         }
31     }
32     
33     return result
34  }
35 }

156ms

 1 class Solution {
 2     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3         
 4         var plateDict = Dictionary(Array(licensePlate).filter{ ("a"..."z").contains(String($0).lowercased()) }.map { (String($0).lowercased(), 1) }, uniquingKeysWith: +)
 5         var length = Int.max
 6         var result = ""
 7         print(plateDict)
 8         for word in words {
 9             let wordDict = Dictionary( word.map{ (String($0).lowercased(), 1) }, uniquingKeysWith: +)
10             if isMatch(plateDict, wordDict) {
11                 if word.count < length {
12                     length = word.count
13                     result = word
14                 }
15             }
16         }
17         return result
18     }
19     
20     fileprivate func isMatch(_ dictA: [String: Int], _ dictB:[String: Int]) -> Bool {
21         for (key, value) in dictA {
22             guard let count = dictB[key] else {
23                 return false
24             }
25             if value > count {
26                 return false
27             }
28         }
29         return true
30     }
31 }

164ms

 1 class Solution {
 2     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3         
 4         var dictLicense: [Character: Int] = [:]
 5         var arrayOfChars = Array(licensePlate).map { Character(String($0).lowercased()) }
 6         
 7         for character in arrayOfChars {
 8             if(character >= "a" && character <= "z") {
 9                             if dictLicense[character] == nil {
10                 dictLicense[character] = 1
11             } else {
12                  dictLicense[character] = dictLicense[character]! + 1
13             }
14             }
15 
16         }
17         
18         //print(dictLicense)
19         
20         let covertedArrayToDicts = words.map { convertkWord($0) }
21         
22         let letIsValidArray = covertedArrayToDicts.map { compare(wordDict: $0, licensePlateDict: dictLicense) }
23         
24         print(letIsValidArray)
25        
26         
27         var maxLength = 20
28         var maxIndex = 0
29         
30         for (index,isValid) in letIsValidArray.enumerated() {
31             
32             if isValid == true {
33                 let word = words[index]
34                 let length = Array(word).count
35                 if length < maxLength {
36                     maxLength = length
37                     maxIndex = index
38                 }
39             }
40             
41         }
42         
43         return words[maxIndex]
44     }
45     
46     func compare(wordDict: [Character:  Int], licensePlateDict: [Character:  Int]) -> Bool {        
47         var copy = wordDict
48 
49         
50         for key in licensePlateDict.keys {
51                         
52             if copy[key] != nil {
53                 
54                 copy[key] = copy[key]! - licensePlateDict[key]!
55 
56                 if copy[key] == 0 {
57                     copy[key] = nil
58                 } else if copy[key]! < 0 {
59                     return false
60                 } else {
61                     
62                 }
63             } else {
64                 return false
65             }
66         }
67         return true
68         
69     }
70     
71     func convertkWord(_ string: String) -> [Character:  Int] {
72         
73         let chars = Array(string)
74         var dict: [Character: Int] = [:]
75         
76         for character in chars {
77             if dict[character] == nil {
78                 dict[character] = 1
79             } else {
80                  dict[character] = dict[character]! + 1
81             }
82             
83         }
84         return dict
85     }
86     
87 }

168ms

 1 class Solution {
 2     func shortestCompletingWord(_ licensePlate: String, _ words: [String]) -> String {
 3         var licensePlate = licensePlate
 4         licensePlate = licensePlate.lowercased()
 5         var pattern = [String:Int]()
 6         for char in licensePlate.unicodeScalars {
 7             if char.value >= 97 && char.value <= 122 {
 8                 pattern["\(char)",default:0] += 1
 9             }
10         }
11         var counts = [String:Int]()
12         var result = ""
13         for word in words {
14             if word.count >= pattern.count {
15                 counts = [String:Int]()
16                 for char in word {
17                     counts["\(char)",default:0] += 1
18                 }
19                 var flag = true
20                 for (k,v) in pattern {
21                     guard let value = counts[k], value >= v else {
22                         flag = false
23                         break
24                     }
25                 }
26                 if flag {
27                     if result == "" {
28                         result = word
29                     }else {
30                         result = word.count < result.count ? word : result
31                     }
32                 }
33             }
34         }
35         return result
36     }
37 }
相關文章
相關標籤/搜索