返回介绍

solution / 0700-0799 / 0771.Jewels and Stones / README_EN

发布于 2024-06-17 01:03:34 字数 3716 浏览 0 评论 0 收藏 0

771. Jewels and Stones

中文文档

Description

You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so "a" is considered a different type of stone from "A".

 

Example 1:

Input: jewels = "aA", stones = "aAAbbbb"
Output: 3

Example 2:

Input: jewels = "z", stones = "ZZ"
Output: 0

 

Constraints:

  • 1 <= jewels.length, stones.length <= 50
  • jewels and stones consist of only English letters.
  • All the characters of jewels are unique.

Solutions

Solution 1

class Solution:
  def numJewelsInStones(self, jewels: str, stones: str) -> int:
    s = set(jewels)
    return sum(c in s for c in stones)
class Solution {
  public int numJewelsInStones(String jewels, String stones) {
    int[] s = new int[128];
    for (char c : jewels.toCharArray()) {
      s[c] = 1;
    }
    int ans = 0;
    for (char c : stones.toCharArray()) {
      ans += s[c];
    }
    return ans;
  }
}
class Solution {
public:
  int numJewelsInStones(string jewels, string stones) {
    int s[128] = {0};
    for (char c : jewels) s[c] = 1;
    int ans = 0;
    for (char c : stones) ans += s[c];
    return ans;
  }
};
func numJewelsInStones(jewels string, stones string) (ans int) {
  s := [128]int{}
  for _, c := range jewels {
    s[c] = 1
  }
  for _, c := range stones {
    ans += s[c]
  }
  return
}
function numJewelsInStones(jewels: string, stones: string): number {
  const s = new Set([...jewels]);
  let ans = 0;
  for (const c of stones) {
    s.has(c) && ans++;
  }
  return ans;
}
use std::collections::HashSet;
impl Solution {
  pub fn num_jewels_in_stones(jewels: String, stones: String) -> i32 {
    let mut set = jewels.as_bytes().iter().collect::<HashSet<&u8>>();
    let mut ans = 0;
    for c in stones.as_bytes() {
      if set.contains(c) {
        ans += 1;
      }
    }
    ans
  }
}
/**
 * @param {string} jewels
 * @param {string} stones
 * @return {number}
 */
var numJewelsInStones = function (jewels, stones) {
  const s = new Set(jewels.split(''));
  return stones.split('').reduce((prev, val) => prev + s.has(val), 0);
};
int numJewelsInStones(char* jewels, char* stones) {
  int set[128] = {0};
  for (int i = 0; jewels[i]; i++) {
    set[jewels[i]] = 1;
  }
  int ans = 0;
  for (int i = 0; stones[i]; i++) {
    set[stones[i]] && ans++;
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文