作者:苗淑香哈哈_405_408 | 来源:互联网 | 2022-12-02 18:24
我想知道给定集合中有多少常见字符.
Input: J = "aA", S = "aAAbbbb"
Output: 3
在python解决方案中,如下所示:
lookup = set(J)
return sum(s in lookup for s in S)
我在Swift中有以下解决方案,但它看起来太罗嗦了.我想学习它的简短方法.
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J) ;
var sy = 0;
for c in S
{
if lookup.contains(c)
{
sy += 1;
}
}
return sy;
}
}
Martin R..
5
作为Sh_Khan答案的一个小变体,您可以使用reduce
来计算匹配元素的数量,而无需创建中间数组:
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.reduce(0) { lookup.contains($1) ? $0 + 1 : $0 }
}
在Swift 5中,将有一个count(where:)
用于此目的的序列方法,参见SE-0220count(where:)
.
1> Martin R..:
作为Sh_Khan答案的一个小变体,您可以使用reduce
来计算匹配元素的数量,而无需创建中间数组:
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.reduce(0) { lookup.contains($1) ? $0 + 1 : $0 }
}
在Swift 5中,将有一个count(where:)
用于此目的的序列方法,参见SE-0220count(where:)
.