l205 isomorphic strings

题目描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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进行映射的判断,相同的字符是否映射相同
  • 使用数组解决

Go实现——使用map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
func (m map[int]int, val int) bool{
for _,v := range m{
if val == v{
return true
}
}
return false
}

func isIsomorphic(s string, t string) bool {
if len(s) != len(t) {
return false
}

m := map[int]int{}

for i:=0;i<len(s);i++ {
c1 := int(s[i])
c2 := int(t[i])
if _,ok:=m[c1]; ok{
if m[c1] != c2 {
return false
}
}else{
if containsVal(m, c2) {
return false
}

m[c1] = c2
}
}

return true
}

Go实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

func isIsomorphic(s string, t string) bool {
if len(s) != len(t) {
return false
}

m1 := make([]int, 256)
m2 := make([]int, 256)

for i:=0;i<len(s); i++ {
if m1[s[i]] != m2[t[i]] {
return false
}

m1[s[i]] = i+1
m2[t[i]] = i+1
}
return true
}

参考资料:http://www.cnblogs.com/grandyang/p/4465779.html