Jewels and Stones Solutions in C++
Number 771
Difficulty Easy
Acceptance 86.4%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/jewels-and-stones/description// Author : Hao Chen// Date : 2018-06-23class Solution {public:int numJewelsInStones(string J, string S) {bool map[256] = {false};for (auto c : J) {map[c]=true;}int cnt=0;for (auto c : S) {if (map[c]) cnt++;}return cnt;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/jewels-and-stones/description//// Author : liuyubobobo/// Time : 2018-10-06#include <iostream>#include <vector>#include <string>#include <unordered_set>using namespace std;/// Brute Force/// Time Complexity: O(len(J) * len(S))/// Space Complxity: O(1)class Solution {public:int numJewelsInStones(string J, string S) {int res = 0;for(char c: S)if(J.find(c) != string::npos)res ++;return res;}};int main() {cout << Solution().numJewelsInStones("aA", "aAAbbbb") << endl;cout << Solution().numJewelsInStones("z", "ZZ") << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/jewels-and-stones/description//// Author : liuyubobobo/// Time : 2018-01-27#include <iostream>#include <vector>#include <string>#include <unordered_set>using namespace std;/// Using Hash Set/// Time Complexity: O(len(J) + len(S))/// Space Complxity: O(len(J))class Solution {public:int numJewelsInStones(string J, string S) {unordered_set<char> jewels;for(char c: J)jewels.insert(c);int res = 0;for(char c: S)if(jewels.find(c) != jewels.end())res ++;return res;}};int main() {cout << Solution().numJewelsInStones("aA", "aAAbbbb") << endl;cout << Solution().numJewelsInStones("z", "ZZ") << endl;return 0;}