• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Swift]LeetCode748.最短完整词|ShortestCompletingWord

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10526316.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 licensePlate

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

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.

Example 1:

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:

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:

  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)中所有的字母,那么我们称之为完整词。在所有完整词中,最短的单词我们称之为最短完整词。

单词在匹配牌照中的字母时不区分大小写,比如牌照中的 "P" 依然可以匹配单词中的 "p" 字母。

我们保证一定存在一个最短完整词。当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。

牌照中可能包含多个相同的字符,比如说:对于牌照 "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(), 
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap