leetcode 771.Jewels and Stones(C++)

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.


题目大意:

  给定两个字符串JS,问J中的字符在S中一共出现过几次
  并且J的值是唯一的

解题思路:

  因为J的值是唯一的,可根据J构建set,然后遍历S
  时间复杂度O(s * j),s和j分别为SJ的大小
  空间复杂度

解题代码:

class Solution {
public:
    int numJewelsInStones(string J, string S) {

        int result =0;
        setjewels;        
        for(size_t i = 0; i < J.size(); ++i)
            jewels.insert(J[i]);
        for(size_t i = 0; i < S.size(); ++i)
            if(jewels.count(S[i]))
                result++;
        return result;

    }
};

        

你可能感兴趣的:(leetcode 771.Jewels and Stones(C++))