771. Jewels and Stones
Description:
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”.
Example1:
Input: J = “aA”, S = “aAAbbbb”
Output: 3
Example2:
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.
Solution:
问题解析:
对于代表石头的字符串S中,每个字母看做一种宝石,那么这个问题就是计算出字符串J中的每个字符在字符串中出现的次数和,其中区分大小写。
思路一:
最笨的思路,遍历字符串S和字符串J,如果字符相同则计数加1
时间复杂度O(J.length*S.length)
空间复杂度O(1)
int sum = 0;
for(char j : J.toCharArray())
{
for(char s : S.toCharArray())
{
if(s == j){
sum ++;
}
}
}
思路二:
利用HashSet这个结构,将宝石作为HashSet的键值key,再遍历字符串S,HashSet中是否已存在这些key值
时间复杂度O(J.length + S.length)
空间复杂度:O(J.length)
class Solution {
public int numJewelsInStones(String J, String S) {
int sum = 0;
Set jewel = new HashSet();
for(char c : J.toCharArray()){
jewel.add(c);
}
for(char c : S.toCharArray()){
if(jewel.contains(c)){
sum ++;
}
}
return sum;
}
}
还没有评论,来说两句吧...