771. Jewels and Stones

You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:

Input: J = "z", S = "ZZ"
Output: 0

Note:

S and J will consist of letters and have length at most 50.
The characters in J are distinct.

这个题目的大体意思是 给你两个字符串。求后面字符串 包含前面字母的个数。

solve

1.开始想着遍历前面的字符串然后去遍历后面的字符串。两个for循环。但是这样做的时间复杂度是 m*n。
2.换种思路。把前面的字符串变成Set 然后遍历后面的字符串 看是否存在即可。此种方式的复杂度为m+n。代码如下。

 func numJewelsInStones(_ J: String, _ S: String) -> Int {
        let jSet = Set(J)
        let sArr = Array(S)
        var count = 0
        for item in sArr{
            if jSet.contains(item){
                count = count+1
            }
        }
        return count
        
    }
  1. 在讨论中看到了一种超级赞的解法。代码如下。
    func numJewelsInStones(_ J: String, _ S: String) -> Int {
           return S.replacingOccurrences(of:"[^"+J+"]", with: "").count
     }

不禁献上了我的膝盖。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,181评论 0 10
  • 题目描述 LeetCode 771 You're given strings J representing th...
    cb_guo阅读 3,073评论 0 0
  • You're given strings J representing the types of stones t...
    顽强的猫尾草阅读 1,877评论 0 0
  • Part 1 玄天大陆,天佑国,冷宫…… 在阴森的冷宫,现任皇后缓缓地走到了苏凤颜的面前,她被铁链绑住了手脚,身上...
    艾伦依儿阅读 1,747评论 0 0
  • 兰花玉指凝如脂, 清水芙蓉貌倾城。 素衣黑发楚动人, 茶花香开真国色。
    东郭笑笑狼阅读 1,549评论 0 0

友情链接更多精彩内容