5月挑战Day2-Jewels and Stones

Day2- 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”.

就是一个寻找字符串中有多少相同字符的题。J由一个或者多个唯一的字符的组成,S由多个字符组成,S里面的字符可以有相同的而J里面的字符都是唯一的,让我们去S里面找和J中字符相同的个数,重复的也算。

Example:

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.

解法一:

暴力解法,遍历J,然后遍历S去S中找到当前的J中的元素,找到的话结果加1.

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        result = 0
        for j in J:
            for s in S:
                if s == j:
                    result += 1
        return result

时间复杂度为O(m*n)–m=len(S);n=len(J).空间复杂度为O(1).

解法二:

以空间换时间,我们设置一个字典存储J中字符的出现次数,遍历S如果S中的字符在字典中出现则相应的值加1,最后把字典中所有元素的值加起来就可以了。

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        result = {}
        for j in J:
            result[j] = 0
        for s in S:
            if s in result:
                result[s] += 1
        R = 0
        for r in result:
            R += result[r]
        return R

空间复杂度为O(m),时间复杂度为O(n)从提交的结果看这两者解法的运算时间差不多。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值