这题似乎可以优化一下,感觉没什么难度也没有练到。。 不怕被大家笑话贴上最开始的代码:
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
gem=[]
stone=[]
counter=0
for i in range(len(J)):
gem.append(J[i])
for j in range(len(S)):
stone.append(S[j])
for k in range(len(S)):
if stone[k] in gem:
counter+=1
return counter
执行用时 : 32 ms, 在Jewels and Stones的Python提交中击败了97.90% 的用户
内存消耗 : 11.9 MB, 在Jewels and Stones的Python提交中击败了7.56% 的用户
试着优化一下:
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
counter=0
for i in range(len(S)):
if S[i] in J:counter+=1
return counter
执行用时 : 32 ms, 在Jewels and Stones的Python提交中击败了97.90% 的用户
内存消耗 : 11.5 MB, 在Jewels and Stones的Python提交中击败了40.64% 的用户
暂时放一下,之后学明白算法了可能回来进行一点有水平的优化