练习5:Jewels and Stones宝石和石头

1、题目链接

  https://leetcode.com/problems/jewels-and-stones/description/

2、题目要求

(1)字符串J代表宝石的类型,字符串S代表拥有的石头

(2)J中每个字母代表一种宝石类型,字母不重复

(3)S中每个字母代表一种石头

(4)J和S中的字母大小写是敏感的

3、解答

 1 class Solution:
 2     def numJewelsInStones(self, J, S):
 3         """
 4         :type J: str
 5         :type S: str
 6         :rtype: int
 7         """
 8         jewels_dict = dict.fromkeys(J, 0)
 9         for stone in S:
10             if stone in jewels_dict:
11                 jewels_dict[stone] += 1
12 
13         count = 0
14         for key, value in jewels_dict.items():
15             count += value
16 
17         return count

4、官方解答

  官方没有解答,但是从别人的解答中可以看到如下这个更加好

 1 class Solution:
 2     def numJewelsInStones(self, J, S):
 3         """
 4         :type J: str
 5         :type S: str
 6         :rtype: int
 7         """
 8         count = 0
 9         for a in S:
10             if a in J:
11                 count += 1
12         return count

5、注意事项

(1)自己的解答画蛇添足,对字符串的遍历理解不够

(2)字符串遍历可以通过sub_str in str来判断一个子串是否在str中,是的话计数加1

猜你喜欢

转载自www.cnblogs.com/hzerdudu/p/9509274.html
今日推荐