zoukankan      html  css  js  c++  java
  • 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))
    

      

  • 相关阅读:
    ES 入门记录之 match和term查询的区别
    ElasticSearch 学习记录之Text keyword 两种基本类型区别
    ES 记录之如何创建一个索引映射,以及一些设置
    娱乐至死 读书笔记
    ES 入门之一 安装ElasticSearcha
    王二的经济学故事 读书笔记
    redis特性 存储 API 集群 等
    Linux 卸载 openjdk
    Linux 下面解压.tar.gz 和.gz文件解压的方式
    本地连接 vmware服务器
  • 原文地址:https://www.cnblogs.com/accumulationbystep/p/10399735.html
Copyright © 2011-2022 走看看