美文网首页leetcode
leetcode 771.Jewels and Stones(C

leetcode 771.Jewels and Stones(C

作者: syuhung | 来源:发表于2019-02-18 17:51 被阅读0次

    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;
            set<char>jewels;        
            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

        本文链接:https://www.haomeiwen.com/subject/qwkzeqtx.html