Swift中的Sum和For循环在一起
我想知道给定集合中有多少个常用字符Swift中的Sum和For循环在一起,swift,Swift,我想知道给定集合中有多少个常用字符 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) -> In
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;
}
}
你可以试试
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.filter { lookup.contains($0) }.count
}
}
你可以试试
class Solution {
func checkInItems(_ J: String, _ S: String) -> Int {
let lookup = Set(J)
return S.filter { lookup.contains($0) }.count
}
}
作为的一个小变体,您可以使用reduce
计算匹配元素的数量,而不创建中间元素
数组:
在Swift 5中,将有一个用于此目的的计数(其中:)
顺序方法,
请参阅。作为的一个小变体,您可以使用减少
计算匹配元素的数量,而不创建中间元素
数组:
在Swift 5中,将有一个用于此目的的计数(其中:)
顺序方法,
请参阅。您想知道任何输入字符在您搜索的字符串中出现的频率吗?您想知道任何输入字符在您搜索的字符串中出现的频率吗?