• [leetcode] 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 Sis 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.

    思路:

      用简单的嵌套循环即可实现。

    c++代码实现:

     1 class Solution {
     2 public:
     3     int numJewelsInStones(string J, string S) {
     4         int num=0;
     5         for(int i=0;i<J.size();i++)
     6         {
     7             for(int j=0;j<S.size();j++)
     8             {
     9                 if(J[i]==S[j])
    10                     num++;
    11             }
    12         }
    13         return num;
    14     }
    15 };

    python代码实现:

    1 class Solution:
    2     def numJewelsInStones(self, J, S):
    3         """
    4         :type J: str
    5         :type S: str
    6         :rtype: int
    7         """
    8         return sum(S.count(j) for j in J)
  • 相关阅读:
    构造函数详解
    左值和左值引用、右值和右值引用
    Lambda函数
    std::thread详解
    运算符重载
    友元函数和友元类
    xadmin list_filter 外键数据不显示
    中缀表达式转后缀表达式
    Centos 7 minimal 联网
    python 运用三目判断对象中多个属性 有且非空
  • 原文地址:https://www.cnblogs.com/guweixin/p/9964125.html
Copyright © 2020-2023  润新知