這個題目思路比較好想,但是邊界問題好難搞亿柑,測了好多次才成功。
題目
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.
解題思路
判斷兩個字符串是否同構(gòu)
建立兩個map棍弄,byteMap用于存儲字符映射關(guān)系望薄,一個用于存儲被映射過的字符,保證一個字符不被映射兩次(一一映射)
- 遍歷s,t, 判斷s[i]是否存在byteMap中呼畸,如果存在痕支,比較映射值和t[i]是否相等,如果相等蛮原,則繼續(xù)下一次遍歷卧须,如果不等,說明兩個字符串不同構(gòu)
- 如果s[i]不存在byteMap中儒陨,需要先判斷s[i], t[i]的值是否相等花嘶,如果相等,把新增映射關(guān)系到Map中蹦漠;如果不相等椭员,需要判斷t[i]是否存在于tMap中,如果存在津辩,說明t[i]已經(jīng)映射過一次拆撼,不能再次映射,返回false喘沿;如果不存在闸度,則把新增映射關(guān)系到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)
}
}
}