-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Leetcode] 771. Jewels and Stones #26
Comments
var numJewelsInStones = function (J, S) {
let count = 0
for (let i = 0; i < S.length; i++) {
if (J.includes(i)) {
count++
}
}
return count
} This is O(n^2). |
var numJewelsInStones = function (J, S) {
// Convert J to object
// No ordering issues like arrays
// KEYS ARE UNIQUE, values are not!
const obj = {}
for (let i = 0; i < J.length; i++) {
obj[J[i]] = 1
}
// For every value in S, if the key in object exists, bam slam.
let counter = 0
for (let i = 0; i < S.length; i++) {
if (obj[S[i]]) {
counter++
}
}
return counter
} This is O(n). Accessing the object is constant time. |
Python Solution. Time: O(J+S)
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Link: https://leetcode.com/problems/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:
Example 2:
The text was updated successfully, but these errors were encountered: