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 inS 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".
Input: J = "aA", S = "aAAbbbb" Output: 3
Input: J = "z", S = "ZZ" Output: 0
Note:
SandJwill consist of letters and have length at most 50.- The characters in
Jare distinct.
Solution
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
int numJewelsInStones(string J, string S) {
int result = 0;
int jlen = J.length();
int slen = S.length();
for (int i = 0; i < slen; i++) {
for (int j = 0; j < jlen; j++) {
if (S[i] == J[j]) {
result++;
break;
}
}
}
return result;
}
};
int main()
{
Solution js;
string Jewels = "aaaaA";
string Stones = "AAAAbbbbbccc";
int numss;
numss = js.numJewelsInStones(Jewels, Stones);
cout << "numss= " << numss << endl;
system("pause");
return 0;
}
本文介绍了一种通过遍历字符串来判断哪些石头属于宝石的方法。输入两个字符串 J 和 S,分别代表宝石类型和拥有的石头,输出属于宝石的石头数量。代码采用双层循环匹配 J 中的每种宝石是否出现在 S 中。

被折叠的 条评论
为什么被折叠?



