205. Isomorphic Strings [easy] (Python)

題目鏈接

https://leetcode.com/problems/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.

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))

PS: 新手刷LeetCode,新手寫博客,寫錯了或者寫的不清楚還請幫忙指出,謝謝!
轉載請註明:http://blog.csdn.net/coder_orz/article/details/51681396

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章