771. Jewels and Stones #
Problem #
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:
SandJwill consist of letters and have length at most 50.- The characters in
Jare distinct.
Problem Summary #
Given string J representing the types of stones that are jewels, and string S representing the stones you have. Each character in S represents a type of stone you have. You want to know how many of the stones you have are jewels.
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.
Solution Approach #
- Given 2 strings, find the number of characters in string S that appear in string J. This is an easy problem.
Code #
package leetcode
import "strings"
// Solution 1
func numJewelsInStones(J string, S string) int {
count := 0
for i := range S {
if strings.Contains(J, string(S[i])) {
count++
}
}
return count
}
// Solution 2
func numJewelsInStones1(J string, S string) int {
cache, result := make(map[rune]bool), 0
for _, r := range J {
cache[r] = true
}
for _, r := range S {
if _, ok := cache[r]; ok {
result++
}
}
return result
}