在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ You're given strings The letters in Example 1: Input: J = "aA", S = "aAAbbbb" Output: 3 Example 2: Input: J = "z", S = "ZZ" Output: 0 Note:
给定字符串
示例 1: 输入: J = "aA", S = "aAAbbbb" 输出: 3 示例 2: 输入: J = "z", S = "ZZ" 输出: 0 注意:
Runtime: 8 ms
Memory Usage: 19.3 MB
1 class Solution { 2 func numJewelsInStones(_ J: String, _ S: String) -> Int { 3 var jewels = [Character : Int]() 4 J.forEach { (c) in 5 jewels[c] = 1 6 } 7 8 return S.reduce(0, { result, c in 9 if let _ = jewels[c] { 10 return result + 1 11 } 12 return result 13 }) 14 } 15 } 8ms 1 class Solution { 2 func numJewelsInStones(_ J: String, _ S: String) -> Int { 3 var count: Int = 0 4 for character in S { 5 if J.contains(character) { 6 count += 1 7 } 8 } 9 return count 10 } 11 } 12ms 1 class Solution { 2 func numJewelsInStones(_ J: String, _ S: String) -> Int { 3 return S.characters.filter{ 4 J.characters.contains($0) 5 }.count 6 } 7 } 16ms 1 class Solution { 2 func numJewelsInStones(_ J: String, _ S: String) -> Int { 3 var res = 0 4 for x in J{ 5 for y in S{ 6 if(y==x){ 7 res+=1 8 } 9 } 10 } 11 return res 12 } 13 } 20ms 1 class Solution { 2 func numJewelsInStones(_ J: String, _ S: String) -> Int { 3 var matchArray: [Character] = [] 4 var stoneArray = Array(S) 5 6 for jewel in J { 7 if stoneArray.contains(jewel) { 8 matchArray += stoneArray.filter { $0 == jewel } 9 } 10 } 11 12 return matchArray.count 13 } 14 } 19064 kb 1 class Solution { 2 func numJewelsInStones(_ J: String, _ S: String) -> Int { 3 var num = 0 4 J.forEach { (Jcharacter) in 5 S.forEach({ (Scharacter) in 6 if Jcharacter == Scharacter { 7 num += 1 8 } 9 }) 10 } 11 12 return num 13 } 14 } 48ms 1 class Solution { 2 func numJewelsInStones(_ J: String, _ S: String) -> Int { 3 var map: [Character:Int?] = [:] 4 for str in J { 5 map[str] = 0 6 } 7 for str in S { 8 if let value = map[str] { 9 map[str] = (value ?? 0) + 1 10 } 11 } 12 return map.values.reduce(0) {$0 + ($1 ?? 0)} 13 } 14 }
|
请发表评论