標題: 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 Sis 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
這題主要是說使用者會輸入2個變數
一個是 J-->寶石種類,另一個是S-->石頭
大小寫有區分
如範例一:
J=aA 就是寶石種類有a和A 二種
S=aAAbbbb 就是一堆石頭,我們發現這堆石頭中有3個寶石aAA
其他bbbb都是石頭,故答案為3個寶石
了解題目,程式碼寫起來就挺容易的
用for迴圈下去做搜尋S陣列,找到跟J陣列一樣的寶石就count++即可囉!!
以下程式碼:
class Solution {
public:
int numJewelsInStones(string J, string S) {
int count=0;
for(int i=0;i<J.size();i++)
{for(int j=0;j<S.size();j++)
{
if(J[i]==S[j]){count++;}
}
}
return count;
}
};
文章標籤
全站熱搜
