S2
S2 copied to clipboard
0205. Isomorphic Strings | LeetCode Cookbook
https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0205.Isomorphic-Strings/
ASCII一共256个字符,其中数值为0的ASCII是Null char是不可被打印的,不用担心它会意外地出现在 s 或 t 中。
func isIsomorphic(s string, t string) bool {
dict, used := [256]byte{}, [256]bool{}
for i, c := range s {
if dict[c] == 0 {
if used[t[i]] {
return false
}
dict[c] = t[i]
used[t[i]] = true
} else if t[i] != dict[c] {
return false
}
}
return true
}
解题思路 这道题做法和第 290 题基本一致
Could be much simpler:
func isIsomorphic(s string, t string) bool {
if len(s) != len(t) {
return false
}
tByte := []byte(t)
sByte := []byte(s)
sMap := map[byte]byte{}
for i, b := range sByte {
if _, ok := sMap[b]; !ok {
sMap[b] = tByte[i]
} else if sMap[b] != tByte[i] {
return false
}
}
return true
}
Verified at https://github.com/suntong/lang/tree/master/lang/Go/src/ds/LeetCode/0205.Isomorphic-Strings