-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRansomNote.php
More file actions
67 lines (61 loc) · 1.72 KB
/
Copy pathRansomNote.php
File metadata and controls
67 lines (61 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
namespace App;
/**
* Ransom Note
*
* Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from
* magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.
*
* Example 1:
* Input: ransomNote = "a", magazine = "b"
* Output: false
*
* Example 2:
* Input: ransomNote = "aa", magazine = "ab"
* Output: false
*
* Example 3:
* Input: ransomNote = "aa", magazine = "aab"
* Output: true
*
* https://leetcode.com/problems/ransom-note
*/
class RansomNote
{
/**
* @param string $ransomNote
* @param string $magazine
* @return bool
*/
public function canConstruct(string $ransomNote, string $magazine): bool
{
/** @var array<array-key, string> $magazineArr */
$magazineArr = str_split($magazine);
$magazineHash = $this->createHash($magazineArr);
/** @var array<array-key, string> $ransomNoteArr */
$ransomNoteArr = str_split($ransomNote);
$ransomNoteHash = $this->createHash($ransomNoteArr);
foreach ($ransomNoteHash as $ransomNoteIndex => $ransomNoteValue) {
if (!(isset($magazineHash[$ransomNoteIndex]) && $magazineHash[$ransomNoteIndex] >= $ransomNoteValue)) {
return false;
}
}
return true;
}
/**
* @param array<array-key, string> $nums
* @return array<array-key, int>
*/
private function createHash(array $nums): array
{
$wordsHash = [];
foreach ($nums as $num) {
if (isset($wordsHash[$num])) {
$wordsHash[$num]++;
} else {
$wordsHash[$num] = 1;
}
}
return $wordsHash;
}
}