[Golang]力扣Leetcode - 205.同构字符串(哈希)

[Golang]力扣Leetcode - 205.同构字符串(哈希)

题目:给定两个字符串 s 和 t ,判断它们是否是同构的。

如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。

每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。

链接力扣Leetcode - 205.同构字符串.

示例 1:

输入:s = “egg”, t = “add”
输出:true

示例 2:

输入:s = “foo”, t = “bar”
输出:false

示例 3:

输入:s = “paper”, t = “title”
输出:true

思路:用两个hash表,最后通过遍历如果 hash1[s[i]] != hash2[t[i]] 输出 false ;其余输出 true 。

Go代码:

package main

import "fmt"

func isIsomorphic(s string, t string) bool {
	if len(s) != len(t) {
		return false
	}
	hash1 := make(map[byte]int)
	hash2 := make(map[byte]int)
	for i := 0; i < len(s); i++ {
		hash1[s[i]] = i
		hash2[t[i]] = i
	}
	for i := 0; i < len(s); i++ {
		if hash1[s[i]] != hash2[t[i]] {
			return false
		}
	}
	return true
}
func main() {
	s := "egg"
	t := "add"
	fmt.Println(isIsomorphic(s, t))
}

提交截图
在这里插入图片描述

posted @ 2022-04-02 22:20  Dancing-Pierre  阅读(16)  评论(0)    收藏  举报  来源