LeetCode 771. Jewels and Stones

771. Jewels and Stones

You're given strings J representing the types of stones that are jewels, and Srepresenting 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 字符串中的每一个字符和 S 中的每一个字符进行匹配,如果能够匹配成功,则统计一次匹配成功。

python 代码:

class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        J_length = len(J)
        S_length = len(S)
        count = 0
        for i in range(J_length):
            for j in range(S_length):
                if J[i] == S[j]:
                    count = count + 1
                    
        return count

C++ 代码:

class Solution {
public:
    int numJewelsInStones(string J, string S) {
        int J_length = J.length();
        int S_length = S.length();
        int count = 0;
        for(int i = 0; i < J_length; i++){
            for(int j = 0; j < S_length; j++){
                if(J[i] == S[j]){
                    count++;
                }
            }
        }
        return count;
    }
};
posted @ 2018-12-18 23:38  Angel_Kitty  阅读(242)  评论(0编辑  收藏  举报