File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed
Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments