LeetCode problem#771
Jewels and Stones
Solved in 2 languagesJavaC#
Solution
20 lines
1class Solution {
2 // time O(n)
3 // space O(n)
4 public int numJewelsInStones(String jewels, String stones) {
5 HashSet<Character> hashSet = new HashSet<Character>();
6 int count = 0;
7
8 for (int i = 0; i < jewels.length(); i++) {
9 hashSet.add(jewels.charAt(i));
10 }
11
12 for (int i = 0; i < stones.length(); i++) {
13 if (hashSet.contains(stones.charAt(i))) {
14 count++;
15 }
16 }
17
18 return count;
19 }
20}1public class Solution {
2 public int NumJewelsInStones(string jewels, string stones) {
3 HashSet<char> hashSet = new HashSet<char>();
4
5 foreach (char c in jewels) {
6 hashSet.Add(c);
7 }
8
9 int count = 0;
10
11 foreach (char c in stones) {
12 if (hashSet.Contains(c)) {
13 count++;
14 }
15 }
16
17 return count;
18 }
19}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Want a walkthrough of this C# solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.