S2 icon indicating copy to clipboard operation
S2 copied to clipboard

0205. Isomorphic Strings | LeetCode Cookbook

Open halfrost opened this issue 4 years ago • 2 comments

https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0205.Isomorphic-Strings/

halfrost avatar Feb 19 '21 13:02 halfrost

ASCII一共256个字符,其中数值为0的ASCII是Null char是不可被打印的,不用担心它会意外地出现在 st 中。

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
}

hanlins avatar Nov 29 '21 21:11 hanlins

解题思路 这道题做法和第 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

suntong avatar Jul 18 '22 04:07 suntong