感觉像是比较字符串;
第一次写:
class Solution(object):
def numJewelsInStones(self, J, S):
“”"
:type J: str
:type S: str
:rtype: int
“”"
count1 = len(J)
count2 = len(S)
i = 0
j = 0
k = 0
while i< count1:
while j < count2:
if (J[i] == S[j]):
k = k+1
return k
想通过两次循环计数,以超时失败;
改进,将S中与J相同的元素删掉(这样的话将字符串转为列表更合适),计算长度;
扩展:
列表去重复;
列表和字符串的主要区别:
列表可被修改,字符串不能,这被称为可变性。
set 或 遍历去重复
list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9]
list2=[]
for i in list1:
if not i in list2:
list2.append(i)
print(list2)
最终:
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
J1 = list(J)
S1 = list(S)
K = 0
i = 0
count1 = len(J1)
count2 = len(S1)
while i < len(S1):
if S[i] in J1:
K = K + 1
else:
K = K
i = i+1
return K
还是用到了比较,将字符串转为列表,将S1中的元素挨个与J1中的元素比较。