Leetcode #771. Jewels and Stones

Posted lhppom

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode #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 Sis 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


题意:给出两个字符串,一个是要匹配的模式串,一个是要匹配的字符串,模式串每个字母都是要匹配的字母,统计目标串中模式串各个字母出现的次数。

想法:最粗暴的想法就是去把模式串中的字母存成像Map或者List的结构数据,然后用的时候去依次扫,如果考虑找是O(1)的话就直接是O(N),(模式串长M,目标串N),如果找是O(M),就是O(MN),目测map的查找应该是O($\sqrt(M)$).后面我的做法是先分别排序,然后合并查找,利用的是两者依然有序的特点。具体可以参考下下面的代码,我看了用一行的做法,是利用了python本身map的用法,map(func, iterable),把func依次作用到iterable的元素上,值得注意的是list.count(str)这个函数,是去匹配list里面出现了多少个str。

我的代码实现:

class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        target = sorted(J)
        source = sorted(S)
        i = len(target)
        j = len(source)
        index1 = 0
        index2 = 0
        cnt = 0
        while index1 < j and index2 < i:
            if source[index1] < target[index2]:
                index1+=1
            elif source[index1] == target[index2]:
                index1+=1
                cnt+=1
            else:
                index2+=1
        return cnt
    
        

  

一行的实现:

def numJewelsInStones(self, J, S):
    return sum(map(J.count, S))

  




以上是关于Leetcode #771. Jewels and Stones的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 771. Jewels and Stones

[leetcode-771-Jewels and Stones]

Leetcode #771. Jewels and Stones

[LeetCode&Python] Problem 771: Jewels and Stones

[LeetCode] 771. Jewels and Stones 珠宝和石头

LeetCode 771:Jewels and Stones