天天看點

​LeetCode刷題實戰205:同構字元串

算法的重要性,我就不多說了吧,想去大廠,就必須要經過基礎知識和業務邏輯面試+算法面試。是以,為了提高大家的算法能力,這個公衆号後續每天帶大家做一道算法題,題目就從LeetCode上面選 !

今天和大家聊的問題叫做 同構字元串,我們先來看題面:

https://leetcode-cn.com/problems/isomorphic-strings/

Given two strings s and t, determine if they are isomorphic.

Two strings s and t 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.

題意

給定兩個字元串 s 和 t,判斷它們是否是同構的。

如果 s 中的字元可以按某種映射關系替換得到 t ,那麼這兩個字元串是同構的。

每個出現的字元都應當映射到另一個字元,同時不改變字元的順序。不同字元不能映射到同一個字元上,相同字元隻能映射到同一個字元上,字元可以映射到自己本身。

示例

示例 1:

輸入:s = "egg", t = "add"
輸出:true

示例 2:

輸入:s = "foo", t = "bar"
輸出:false

示例 3:

輸入:s = "paper", t = "title"
輸出:true
           

解題

判斷每個字元的索引相同,如果後面有重複的字元,index就會直接索引到第一次出現的位置。相當于同一字元第一個出現的位置映射到字元串中所有相同的字元。

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        for i in range(len(s)):
            if s.index(s[i]) != t.index(t[i]):
                return False
        return True
           

好了,今天的文章就到這裡,如果覺得有所收獲,請順手點個在看或者轉發吧,你們的支援是我最大的動力 。

上期推文:

LeetCode1-200題彙總,希望對你有點幫助!

LeetCode刷題實戰201:數字範圍按位與

LeetCode刷題實戰202:快樂數

LeetCode刷題實戰203:移除連結清單元素

LeetCode刷題實戰204:計數質數

​LeetCode刷題實戰205:同構字元串