205. Isomorphic Strings [easy] (Python)
題目連結
題目原文
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.
題目翻譯
給定兩個字串,判斷它們是否是同構的。如果一個字串s中的字元可以替換成別的字元,從而得到另一個字串t,那麼兩個字元串同構。
字串中所有的一樣的字元都要替換,並且要保持原順序。兩個不同的字元不能替換成相同的字元,一個字元可以替換成它自己。
比如:
給定 "egg"
, "add"
, 返回 true
給定 "foo"
, "bar"
, 返回 false
給定 "paper"
, "title"
, 返回 true
注意:假設兩個字串s和t的長度相同。
思路方法
思路一
先遍歷一遍s和t,將s到t的字元對映存放在dict中,遍歷過程中如果發現某個位置的對映與已經確定的對映衝突則可以直接返回false。但這個過程無法發現“不同的字元對映到相同的字元”這一情況,所以最後還要判斷得到的對映關係是否有重複。
程式碼
class Solution(object):
def isIsomorphic(self, s, t) :
"""
:type s: str
:type t: str
:rtype: bool
"""
hashmap = {}
for i in xrange(len(s)):
if s[i] not in hashmap:
hashmap[s[i]] = t[i]
elif hashmap[s[i]] != t[i]:
return False
mapval = [hashmap[k] for k in hashmap]
return len(mapval) == len(set(mapval))
思路二
類似上面的思路,為了避免在最後對hashmap中的值做“是否有重複”的判斷,在遍歷s和t的時候將已經經過對映的值儲存在mapval這個dict中,這樣在中途發現重複時也可以及時返回false。
程式碼
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
hashmap = {}
mapval = {}
for i in xrange(len(s)):
if s[i] in hashmap:
if hashmap[s[i]] != t[i]:
return False
elif t[i] in mapval:
return False
else:
hashmap[s[i]] = t[i]
mapval[t[i]] = True
return True
思路三
對於s和t,分別用一個數組記錄每個字元在該字串中上一次出現的位置。當同時遍歷s和t時,如果發現它們在某一位置的字元上次出現的位置不同,則返回false。
程式碼
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
pos1, pos2 = [-1]*256, [-1]*256
for i in xrange(len(s)):
if pos1[ord(s[i])] != pos2[ord(t[i])]:
return False
pos1[ord(s[i])] = pos2[ord(t[i])] = i
return True
思路四
與思路三類似,相當於思路三記錄上次出現位置,而現在記錄第一次出現的位置。
對於s,遍歷將其每個字元第一次出現的位置記錄成一個新的陣列;對t做同樣的處理。如果得到的兩個陣列相同,則說明這是一個符合要求的對映,s和t同構;否則不同構。
用Python的內建函式map和字串的find函式,可以一行實現。
程式碼
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return map(s.find, s) == map(t.find, t)
思路五
根據題目描述的對映要求,s有多少種不同的字元,t也有多少種不同的字元。如果我們將對映寫成字元對的形式,比如 (‘a’,’c’) 表示s中字元’a’對映到t中’c’,那麼對映的個數與s中字元的種類數相同。
用Python的內建函式zip,也可以一行實現判斷同構。
程式碼
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return len(set(zip(s, t))) == len(set(s)) == len(set(t))