LeetCode刷题笔记(一)
2018-03-16 20:05 cocolkk 阅读(229) 评论(0) 收藏 举报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".
题目挺简单的,大概意思是:键盘输入字符串J,S;若S字符串中含有的字母J字符串也有,J中的字母被视为宝石,S中部和J中字母相同的字母被定义为石头;
错误代码:
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
count = 0
for s in S:
if s in J:
count += 1
return count
J = input("请输入字符串:")
S = input("请输入字符串:")
s1 = Solution()
res = s1.numJewelsInStones(J, S)
print(res)
正确代码:
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
count = 0
for s in S:
if s in J:
count += 1
return count
# J = "aA"
# S = "aAAbbbb"
# s1 = Solution()
# res = s1.numJewelsInStones(J, S)
# print(res)
在LeetCode上提交代码时不用自己创建对象,也不用自己调用,还有一种方法:
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
count = 0
for s in S:
for j in J:
if s==j:
count += 1
return count
浙公网安备 33010602011771号