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.
根据题意来看,因为直接给我们的就是长度相同的两个字符串,那么直接写代码检查判断是否是相同的结构就可以。这个相同结构,简单来说就是,如果有相同的字符,那么如果出现在的index是一样的,那么就是相同结构的字符串。
首先想到用hash来做,构建一个dictionary,{}。
class Solution(object):
def isIsomorphic(self, s, t):
dic1 = self.createDic(s)
dic2 = self.createDic(t)
return sorted(dic1.values()) == sorted(dic2.values())
def createDic(self, strings):
dic = {}
for c in range(len(strings)):
if strings[c] not in dic:
dic[strings[c]] = [c]
else:
dic[strings[c]].append(c)
return dic
对两个字符串,字符作为key,index作为value。只要values的值相同,那么两个字符串的结构就是一样的。
=======================
因为题意就是为了判断,两个字符串是否同样的字符所在的index相同。转换下思想,把字符串s的字符当做key,字符串t的字符当做value。只要达到要求,两个字符串的字符两两对应,那么结构就相同。
class Solution(object):
def isIsomorphic(self, s, t):
dic = {}
for i in range(len(s)):
if s[i] in dic:
if not dic[s[i]] == t[i]:
return False
else:
if t[i] in dic.values():
return False
dic[s[i]] = t[i]
return True
Pythonic的方法
def isIsomorphic(self, s, t):
return len(set(zip(s, t))) == len(set(s)) == len(set(t))
set("paper") # set(['a', 'p', 'r', 'e'])
set("title") # set(['i', 'e', 't', 'l'])
zip("paper", "title") # [('p', 't'), ('a', 'i'), ('p', 't'), ('e', 'l'), ('r', 'e')]
zip之后,如果结构不同,最后的length会不同。
def isIsomorphic(self, s, t):
return [s.find(i) for i in s] == [t.find(j) for j in t]
["paper".find(i) for i in "paper"] # [0, 1, 0, 3, 4]
find方法,找到所有字符在字符串中的index。如果结构相同,得到的index的List是相同的。
def isIsomorphic(self, s, t):
return map(s.find, s) == map(t.find, t)
"paper".find # <built-in method find of str object at 0x1033eff90>
map("paper".find, "paper") # [0, 1, 0, 3, 4]
就是跟之前的方法差不多,用了map和find一起,也是找到并返回一个index的list。