Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the problem of gemstones and stones in leetcode

Shulou Source: shulou.com Published: 2022-06-01 01:05:28 11月13日 Update

This article mainly shows you "how to solve the problem of gems and stones in leetcode", the content is simple and easy to understand, and the organization is clear. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "how to solve the problem of gems and stones in leetcode".

Title Link

https://leetcode-cn.com/problems/jewels-and-stones/

Title Description

Given the string J represents the type of gem in the stone, and the string S represents the stone you own. Each character in S represents a type of stone you own, and you want to know how many of the stones you own are gems.

The letters in J are not repeated, and all characters in J and S are letters. Letters are case-sensitive, so "a" and "A" are different types of stones.

Example 1:

Input: J = "aA", S = "aAAbbbb"

Output: 3

Example 2:

Input: J = "z", S = "ZZ"

Output: 0

Note:

S and J contain up to 50 letters.

The characters in J are not repeated.

solution train of thought

Tag: string

J is traversed first, and the characters are stored in HashSet respectively, so that they can be searched later when traversing S.

Traversing S and comparing each character with those in HashSet, if any, the result is ans++, the traversal ends, returning ans

Time complexity: O(m+n), m is the length of J, n is the length of S

code

Java version

class Solution {

public int numJewelsInStones(String J, String S) {

Set set = new HashSet();

for(int i = 0; i

< J.length(); i++) { set.add(J.charAt(i)); } int ans = 0; for(int i = 0; i < S.length(); i++) { if(set.contains(S.charAt(i))){ ans++; } } return ans; } } JavaScript版本 /** * @param {string} J * @param {string} S * @return {number} */ var numJewelsInStones = function(J, S) { const set = new Set(); for(const s of J) { set.add(s); } let ans = 0; for(const s of S) { if(set.has(s)){ ans++; } } return ans; }; 画解

The above is "how to solve the problem of gems and stones in leetcode" all the contents of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Tags: Stone character gem letter question representative content string article type version example length topic learning help input output different complex Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Docker Linux MariaDB Huawei