-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisAnagram.php
54 lines (46 loc) · 1.34 KB
/
isAnagram.php
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
<?php
// https://leetcode.com/problems/ransom-note/description/?envType=study-plan-v2&envId=top-interview-150
class Solution
{
/**
* @param String $s
* @param String $t
* @return Boolean
*/
function isAnagram($s, $t)
{
$stringLength1 = strlen($s);
$stringLength2 = strlen($t);
if($stringLength1 != $stringLength2){
return false;
}
$availableLetters = $this->createHashMap($s);
for ($i = 0; $i < $stringLength1; $i++) {
if(!isset($availableLetters[$t[$i]])){
return false;
}
if ($availableLetters[$t[$i]] ) {
$availableLetters[$t[$i]] = $availableLetters[$t[$i]] - 1;
continue;
}
return false;
}
return true;
}
private function createHashMap($s): array
{
$hashMap = [];
for ($i = 0; $i < strlen($s); $i++) {
$hashMap[$s[$i]] = isset($hashMap[$s[$i]]) ? $hashMap[$s[$i]] + 1 : 1;
}
echo json_encode($hashMap) . PHP_EOL;
return $hashMap;
}
}
$solution = new Solution();
$s = "anagram";
$t = "nagaram";
echo ($solution->isAnagram($s, $t) == true ? "PASSED" : "FAILED") . PHP_EOL;
$s = "rat";
$t = "car";
echo ($solution->isAnagram($s, $t) == false ? "PASSED" : "FAILED") . PHP_EOL;