Day2- 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里面的字符都是唯一的,让我们去S里面找和J中字符相同的个数,重复的也算。
Example:
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.
解法一:
暴力解法,遍历J,然后遍历S去S中找到当前的J中的元素,找到的话结果加1.
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
result = 0
for j in J:
for s in S:
if s == j:
result += 1
return result
时间复杂度为O(m*n)–m=len(S);n=len(J).空间复杂度为O(1).
解法二:
以空间换时间,我们设置一个字典存储J中字符的出现次数,遍历S如果S中的字符在字典中出现则相应的值加1,最后把字典中所有元素的值加起来就可以了。
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
result = {}
for j in J:
result[j] = 0
for s in S:
if s in result:
result[s] += 1
R = 0
for r in result:
R += result[r]
return R