Jewels and Stones(计算一个字符串中的字符累计在另一个字符串中出现的次数)

题目: 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 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.



  • 两个字符串的嵌套循环


  public int numJewelsInStones(String J, String S) {
      // 分别获取每个字符串的字符数组
      char[] js = J.toCharArray();
      char[] ss = S.toCharArray();

      int count = 0;

      // 嵌套循环,判断如果有相等的则次数加1
      for(char i:js) {
          for(char l:ss) {
              if (i == l) {
                  count ++ ;
      return count;

声明??php $this->options->title() ?>|版权所有,违者必究|如未注明,均为原创|本网站采?a href="" target="_blank">BY-NC-SA协议进行授权

转载:转载请注明原文链接 - Jewels and Stones(计算一个字符串中的字符累计在另一个字符串中出现的次数)