[leetcode]205. Isomorphic Strings

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

判断两个字符串是否同构,即s中的每个字符是否可以和t中的字符一一对应,每个字符只能对应除了自身外唯一的值

解法1:

1 class Solution(object):
2     def isIsomorphic(self, s, t):
3         return [s.find(i) for i in s] == [t.find(i) for i in t]

解法2:

1 class Solution(object):
2     def isIsomorphic(self, s, t):
3         return map(s.find,s) == map(t.find,t)

解法3:

1 class Solution(object):
2     def isIsomorphic(self, s, t):
3         return len(set(zip(s,t))) == len(set(s)) == len(set(t))

解法4:

1 class Solution(object):
2     def isIsomorphic(self, s, t):
3         ds = collections.defaultdict(list)
4         dt = collections.defaultdict(list)
5         for i,c in enumerate(s):
6             ds[c].append(i)
7         for i,c in enumerate(t):
8             dt[c].append(i)
9         return sorted(ds.values())==sorted(dt.values())

 

posted @ 2017-03-05 20:30  wilderness  阅读(140)  评论(0编辑  收藏  举报