• 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".

    (1) -> 常常出现在函数名后面,描述函数的返回类型,如:

    def add(x,y)->int: #函数的返回类型为int

        return x+y

    (2)@property是一个装饰器,能够使得类把一个方法变成属性调用。如:

    class Student(object):

        @property

        def score(self):

            return self._score

        @score.setter

        def score(self,value):

            if not isinstance(value,int):

                raise ValueError('score must be an integer!')

            if score<0 or score>100:

                raise ValueError('score must between 0~180')

            self._score = value

    s = Student()

    s.score = 60

    s.score = 9999 #ValueError

    (3)解题:

    class Solution:
        def numJewelsInStones(self, J:'str', S:'str') -> 'int':
            num = 0
            for s in S:
                if s in J:
                    num += 1
            return num
    
    s = Solution()
    n = s.numJewelsInStones("z","ZZ")
    print(n)

     优化:    

    class Solution:
        def numJewelsInStones(self, J:'str', S:'str') -> 'int':
            return sum(s in J for s in S)
    
    s = Solution()
    n = s.numJewelsInStones("z","ZZ")
    print(n)
    
    
    #方法二:使用str的count属性
    def numJewelsInStones(self, J:'str', S:'str') -> 'int':
            return sum(map(S.count,J))
    

      

  • 相关阅读:
    Node中js获取异步操作的结果
    阿里云服务器(一)——Nodejs环境配置
    Nodejs之路(二)—— Nodejs再入门
    通过IDEA制作包含Java应程序的Docker镜像
    IDEA远程调试Tomcat程序
    思维导图_脑图
    gitlab userguide
    如何渲染MARKDOWN与MATHJAX
    markdown emoji表情包
    changing-a-remote-s-url
  • 原文地址:https://www.cnblogs.com/accumulationbystep/p/10399735.html
Copyright © 2020-2023  润新知