leetcode- 771. Jewels and Stones(宝石和石头)
自己动手做的leetcode第一题(被女朋友逼着做的。。。)
771. 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".
Example 1:
Input: J = "aA", S = "aAAbbbb" Output: 3
Example 2:
Input: J = "z", S = "ZZ" Output: 0
Note:
SandJwill consist of letters and have length at most 50.- The characters in
Jare distinct.
体验:
零基础coding真是蛋疼啊,慌的要死。
1. strings 代表什么类型?怎么取长度?操作
思路:从J【0】开始与J[J.size()]里的元素分别对比,相同则sum+1,不同则跳过。
遇到问题:1. string类型的J和S, 如何取其中某个元素?(本题按照数组形式)
2. string类型J 和S 的长度如何得到?(是S.size()还是sizeof(S)??)
class Solution {
public:
int numJewelsInStones(string J, string S) {
int sum=0;
int i,j;
for(i=0;i<J.size();i++)
{
for(j=0;j<S.size();j++)
{
if (J[i]==S[j])
sum++;
}
}
return sum;
}
};
浙公网安备 33010602011771号