1. 程式人生 > >LeetCode771. Jewels and Stones

LeetCode771. Jewels and Stones

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:

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

 題目:計算字串S中有多少個字元是在字串J中出現過的.注意:字串J中的字元均是不同的.

Solution1.對字串J建立一個map或者set,然後依次判斷S中的字元是否在J中.

Solution2:因為S和J中的字元僅有大小寫的英文字元,可利用ASCII碼錶,建立一個大小為128的陣列char_num,先統計S中的每個字元出現的次數,然後對J中的每個字元,在陣列char_num中查詢其對應的值.

#include<unordered_map>
#include<iostream>
using namespace std;

class Solution {
public:
    int numJewelsInStones(string J, string S) {
        unordered_map<char, int> char_num;
        int res = 0;
        for(const auto &c : J){
            char_num[c] = 1;
        }
        
        //判斷Stone中的每個元素是否在Jewels中
        for(const auto &c: S){
            auto iter = char_num.find(c);
            if(iter != char_num.end())
                res++;
        }
        return res;
    }
};

class Solution2 {
public:
    int numJewelsInStones(string J, string S) {
        int res = 0;
        //只有大小寫字母,對應的ASCII碼A:65,a:97.
        int char_num[128] = {0};
        for(const auto &c : S){
            char_num[c]++;
        }
        
        //對於Jewels中的每個元素,在Stone對應的char_num陣列中查詢
        for(const auto &c: J){
            res += char_num[c];
        }
        return res;
    }
};

int main(int argc, char const *argv[])
{
    Solution sln;
    cout << sln.numJewelsInStones("aA", "aAAbbbb") << endl;
    return 0;
}