【LeetCode】771. 宝石与石头

135 阅读2分钟

image.png

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第19天,点击查看活动详情

测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。 么才能提高我们的编程能力呢,刷Le0etCode是最佳的途径之一,话不多数,刷题走起~

一、题目描述:

  • 题目内容

    image.png

  • 题目示例

    image.png

  • 题目解析

    • 本题有两个参数,字符串stones和字符串jewels。
    • 字符串stones和字符串jewels,要区分大小写

二、思路分析:

我们拿到本题,读完题意之后,要求在字符串jewels字符在字符串stones出现次数。

  • 方法一:暴力求解

  • 解答该题,我们可以直接使用暴力求解,思路比较清晰:

    • 直接使用两个for循环遍历
    • 第一层for循环遍历字符串jewels,取出字符i
    • 第二层for循环遍历字符串stones取出字符j
    • 判断字符i与字符j是否相等,如果相等则ans加一
    • 直到遍历jewels字符串,返回ans

    根据以上思路,我们使用python可以轻松实现,代码如下:

    class Solution(object):
        def numJewelsInStones(self, jewels, stones):
            """
            :type jewels: str
            :type stones: str
            :rtype: int
            """
    
            ans = 0
            for i in range(len(jewels)):
    
                for j in range(len(stones)):
    
                    if jewels[i] == stones[j]:
                        ans = ans +1
    
            return ans
    
    

使用两个for循环,虽然可以实现该题,但是时间复杂度O(n^2)效率比较低

  • 方法二:哈希集

    • 那有什么方法,只是使用一个for循环?

      • 使用一个for循环遍历stones,取出字符j
      • 判断取出的字符j是否在jewels字符串中,如在则ans加1
    class Solution(object):
        def numJewelsInStones(self, jewels, stones):
            """
            :type jewels: str
            :type stones: str
            :rtype: int
            """
    
            ans = 0
    
            for j in range(len(stones)):
    
                if  stones[j] in jewels:
                    ans = ans +1
    
            return ans
    
  • 方式三:count()函数

    • 在python中,我们仍然可以使用count函数来解答该题

      • 一行代码就可以搞定
      return sum(stones.count(j) for j in jewels)
      

三、总结:

我们使用方法二哈希表思想来解答,AC提交记录如下:

image.png

时间复杂度O(n+m),n是stones字符串长度,m是jewels字符串长度 空间复杂度O(m),m是jewels字符串长度

以上是本期内容,欢迎大佬们点赞评论,下期见~~~