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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章