Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 0 additions & 26 deletions src/JewelsAndStones771.java

This file was deleted.

40 changes: 40 additions & 0 deletions src/main/java/com/leetcode/easy/JewelsAndStones771.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Tags: String, Hash Set
package com.leetcode.easy;

import java.util.HashSet;
import java.util.Set;

public class JewelsAndStones771 {
/*
Time complexity: O(J + S)
Breakdown:
- First loop: Iterates through the jewels string of length J, adding each character to the HashSet
- Each add() operation on HashSet takes O(1) average time
- Total: O(J)
- Second loop: Iterates through the stones string of length S, checking if each character exists in the HashSet
- Each contains() operation on HashSet takes O(1) average time
- Total: O(S)
- Overall: O(J) + O(S) = O(J + S)
Where J is the length of the jewels string and S is the length of the stones string.

Space complexity: O(J)
Breakdown:
- HashSet storage: The jewelsTypes HashSet stores at most J unique characters from the jewels string
- In the worst case, all characters in jewels are unique, requiring O(J) space
- Other variables: res and loop variables use O(1) constant space
- Overall: O(J)
*/
public int numJewelsInStones(String jewels, String stones) {
Set<Character> jewelsTypes = new HashSet<>();
for (int i = 0; i < jewels.length(); i++) {
jewelsTypes.add(jewels.charAt(i));
}
int res = 0;
for (int i = 0; i < stones.length(); i++) {
if (jewelsTypes.contains(stones.charAt(i))) {
res++;
}
}
return res;
}
}
35 changes: 35 additions & 0 deletions src/test/java/com/leetcode/easy/JewelsAndStones771Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.leetcode.easy;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class JewelsAndStones771Test {
private JewelsAndStones771 solution;

@BeforeEach
void setUp() {
solution = new JewelsAndStones771();
}

@Test
void testNumJewelsInStones_Example1() {
String jewels = "aA";
String stones = "aAAbbbb";

int result = solution.numJewelsInStones(jewels, stones);

assertEquals(3, result);
}

@Test
void testNumJewelsInStones_Example2() {
String jewels = "z";
String stones = "ZZ";

int result = solution.numJewelsInStones(jewels, stones);

assertEquals(0, result);
}
}