Sum和For循环一起在Swift中

cas*_*las 1 swift

我想知道给定集合中有多少常见字符.

Input: J = "aA", S = "aAAbbbb"
Output: 3
Run Code Online (Sandbox Code Playgroud)

在python解决方案中,如下所示:

lookup = set(J)
return sum(s in lookup for s in S)
Run Code Online (Sandbox Code Playgroud)

我在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n 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 }
}
Run Code Online (Sandbox Code Playgroud)

在Swift 5中,将有一个count(where:)用于此目的的序列方法,参见SE-0220count(where:).