这个题目思路比较好想,但是边界问题好难搞,测了好多次才成功。
题目
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Note:
You may assume both s and t have the same length.
解题思路
判断两个字符串是否同构
建立两个map,byteMap用于存储字符映射关系,一个用于存储被映射过的字符,保证一个字符不被映射两次(一一映射)
- 遍历s,t, 判断s[i]是否存在byteMap中,如果存在,比较映射值和t[i]是否相等,如果相等,则继续下一次遍历,如果不等,说明两个字符串不同构
- 如果s[i]不存在byteMap中,需要先判断s[i], t[i]的值是否相等,如果相等,把新增映射关系到Map中;如果不相等,需要判断t[i]是否存在于tMap中,如果存在,说明t[i]已经映射过一次,不能再次映射,返回false;如果不存在,则把新增映射关系到Map中
- 如果所有s[i] -> t[i]都能保证一一映射,则返回true
代码
isomorphicStrings.go
package _205_Isomorphic_Strings
func IsIsomorphic(s string, t string) bool {
var byteMap map[byte]byte
byteMap = make(map[byte]byte)
var tMap map[byte]bool
tMap = make(map[byte]bool)
len1 := len(s)
for i := 0; i < len1; i++ {
tmp, ok := byteMap[s[i]]
if ok {
if tmp != t[i] {
return false
}
} else {
if s[i] != t[i] {
_, ok1 := tMap[t[i]]
if ok1 {
return false
}
}
byteMap[s[i]] = t[i]
tMap[t[i]] = true
}
}
return true
}
测试
isomorphicStrings_test.go
package _205_Isomorphic_Strings
import "testing"
func TestIsIsomorphic(t *testing.T) {
var tests = []struct{
s string
t string
output bool
} {
{"egg", "add", true},
{"foo", "bar", false},
{"paper", "title", true},
{"ab", "aa", false},
{"aa", "ab", false},
{"aba", "baa", false},
}
for _, v := range tests {
ret := IsIsomorphic(v.s, v.t)
if ret == v.output {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", v.output, ret)
}
}
}