-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIsomorphicStrings.php
57 lines (47 loc) · 1.35 KB
/
IsomorphicStrings.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
54
55
56
57
<?php
namespace QueueAndStack\HashMap\IsomorphicStrings;
// 给定两个字符串 s 和 t,判断它们是否是同构的。
//
// 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。
//
// 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
//
// 示例 1:
//
// 输入: s = "egg", t = "add"
// 输出: true
// 示例 2:
//
// 输入: s = "foo", t = "bar"
// 输出: false
// 示例 3:
//
// 输入: s = "paper", t = "title"
// 输出: true
// 说明:
// 你可以假设 s 和 t 具有相同的长度。
class Solution
{
/**
* @param String $s
* @param String $t
* @return Boolean
*/
function isIsomorphic($s, $t)
{
$sKeyMap = [];
$tKeyMap = [];
for ($i = 0, $l = strlen($s); $i < $l; ++ $i) {
$sChar = $s{$i};
$tChar = $t{$i};
$sIndex = $sKeyMap[$sChar] ?? -1;
$tIndex = $tKeyMap[$tChar] ?? -1;
if ($sIndex !== $tIndex) {
return false;
}
$sKeyMap[$sChar] = $i;
$tKeyMap[$tChar] = $i;
}
return true;
}
}