LeetCode-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

Note:

  • S and J will consist of letters and have length at most 50.
  • The characters in J are distinct.


翻譯:

你被給定字符串 J 表示石頭類型是珠寶, S 表示你有的石頭。每一個 S 中的字符是一種你擁有的石頭。你想知道你擁有的多少石頭同時也是珠寶。

J 中的字母保證是不同的,並且 J  S 中的所有字符都是字母。字母大小寫敏感,因此,"a" 被看作是和 "A"不同的。

例子1:

輸入: J = "aA", S = "aAAbbbb"
輸出: 3

例子2:

輸入: J = "z", S = "ZZ"
輸出: 0

注意:

  • S 和 J包含的字符長度不超過50。
  • J 中的字符是不同的。

思路:

用set存儲 J 中不同的字符。然後掃描 S 中的字符看是否在set中,若在,則說明是珠寶,結果result++。


C++代碼(Visual Studio2017):

#include "stdafx.h"
#include <iostream>
#include <string>
#include <set>
using namespace std;

class Solution {
public:
	int numJewelsInStones(string J, string S) {
		int result=0;
		set<char> setJ(J.begin(), J.end());
		for (char s : S)
			if (setJ.count(s))
				result++;
		return result;
	}
};

int main()
{
	Solution s;
	string J = "aA";
	string S = "aAAbbbb";
	int result;
	result = s.numJewelsInStones(J, S);
	cout << result;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章