Skip to content

Commit 3644267

Browse files
committed
Ransom Note
1 parent 313f047 commit 3644267

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package leetcode.easy;
2+
3+
public class RansomNote {
4+
5+
boolean canConstruct(String ransomNote, String magazine) {
6+
int[] charCount = new int[26];
7+
8+
// Count the frequency of each character in the magazine
9+
for (char c : magazine.toCharArray()) {
10+
charCount[c - 'a']++;
11+
}
12+
13+
// Check if we can construct the ransom note
14+
for (char c : ransomNote.toCharArray()) {
15+
if (charCount[c - 'a'] == 0) {
16+
return false; // Character not available in magazine
17+
}
18+
charCount[c - 'a']--;
19+
}
20+
21+
// Ransom note can be constructed
22+
return true;
23+
}
24+
25+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package leetcode.easy;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class RansomNoteTest {
8+
9+
private final RansomNote ransomNote;
10+
11+
RansomNoteTest() {
12+
ransomNote = new RansomNote();
13+
}
14+
15+
@Test
16+
void testCanConstruct1() {
17+
String ransomNoteStr = "a";
18+
String magazineStr = "b";
19+
assertFalse(ransomNote.canConstruct(ransomNoteStr, magazineStr));
20+
}
21+
22+
@Test
23+
void testCanConstruct2() {
24+
String ransomNoteStr = "aa";
25+
String magazineStr = "ab";
26+
assertFalse(ransomNote.canConstruct(ransomNoteStr, magazineStr));
27+
}
28+
29+
@Test
30+
void testCanConstruct3() {
31+
String ransomNoteStr = "aa";
32+
String magazineStr = "aab";
33+
assertTrue(ransomNote.canConstruct(ransomNoteStr, magazineStr));
34+
}
35+
}

0 commit comments

Comments
 (0)