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.
第一次作答:
class Solution: def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ s_dict = {} t_dict = {} tmp_s = "" tmp_t = "" for tmp_c in s: if tmp_c in s_dict: s_dict[tmp_c] += 1 else: s_dict[tmp_c] = 1 tmp_s += str(s_dict[tmp_c]) for tmp_c in t: if tmp_c in t_dict: t_dict[tmp_c] += 1 else: t_dict[tmp_c] = 1 tmp_t += str(t_dict[tmp_c]) if tmp_s == tmp_t: return True else: return False
这次作答的主要问题是:只记录了每个字符出现的次数,以次数来表明是否同构,出错了“aba”和“baa”,因为显示结果都是112.
第二次作答:
class Solution: def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ return [s.find(i) for i in s] == [t.find(j) for j in t]
通过字符串的find方法,获取到所有第i个字符出现的索引值,没有强调具体是哪个字符,但是指明了顺序
第二种方式:
class Solution: def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ d1, d2 = {}, {} for i, val in enumerate(s): # 这里可以记录一个val出现的顺序,刚才自己写的部分就忽略了这个问题 d1[val] = d1.get(val, []) + [i] for i, val in enumerate(t): d2[val] = d2.get(val, []) + [i] return sorted(d1.values()) == sorted(d2.values())
下面是一个输入与输出的例子:我们记录了每个字符是什么,并且出现的位置是多少,用sorted来表示是否同构的意思,因为我们并不关注字符是否相同,只是某些字符出现的位置是否一致。
Your input
"egg" "add"
Your stdout
{'g': [1, 2], 'e': [0]}
{'a': [0], 'd': [1, 2]}