给定字符串J 代表石头中宝石的类型,和字符串 S 代表你拥有的石头。S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。J 中的字母不重复,J 和 S 中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
最直接的暴力法
#include <iostream>
using namespace std;
int main()
{
char J[50]={'a','A'};
char S[50]={'a','A','A','S','S'};
int count =0;
for(int i=0;i<strlen(S);i++)
{
for(int j=0;j<strlen(J);j++)
{
if(J[j]==S[i])
count++;
}
}
cout<<count<<endl;
return 0;
}
力扣的高级方法
把宝石类型J记录进set中,用count函数一块块鉴定所拥有的石头是否属于set内的任意一个。若是,ans加一。
关于模板函数,放在这个里边 介绍
https://blog.csdn.net/deeplan_1994/article/details/83111895?ops_request_misc=&request_id=&biz_id=102&utm_term=%20unordered_set%5C%3Cchar%5C%3E%20jew;&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-9-83111895
class Solution {
public:
int numJewelsInStones(string J, string S) {
int ans = 0;
unordered_set<char> jew;
for(auto i : J) jew.insert(i); //记录宝石类型
for(auto s : S) if(jew.count(s)) ++ ans; //若拥有的石头里有宝石,答案加一
return ans;
}
};
作者:youlookdeliciousc
链接:https://leetcode-cn.com/problems/jewels-and-stones/solution/cxiang-xi-ti-jie-ji-jian-by-youlookdeliciousc/
来源:力扣(LeetCode)
在java中用哈希表的方法也不错
class Solution {
public int numJewelsInStones(String J, String S) {
Set<Character> Jset = new HashSet();
for (char j: J.toCharArray())
Jset.add(j);
int ans = 0;
for (char s: S.toCharArray())
if (Jset.contains(s))
ans++;
return ans;
}
}