天天看點

LeetCode 205:同構字元串 Isomorphic Strings

題目:

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

如果 s 中的字元可以被替換得到 *t* ,那麼這兩個字元串是同構的。

所有出現的字元都必須用另一個字元替換,同時保留字元的順序。兩個字元不能映射到同一個字元上,但字元可以映射自己本身。

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.

示例 1:

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

示例 2:

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

示例 3:

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

說明:

你可以假設 s 和 *t* 具有相同的長度。

Note:

You may assume both s* and t* have the same length.

解題思路:

​ 在示例 3 中輸入:

s = "paper", t = "title"

,其中字母映射結果:

p <==> t , a <==>i , e <==> l , r <==>e

映射的字母可以一一替換得到對應的單詞,這便是同構字元串。

非同構字元串無非兩種情況(假設長度相等):

  • s = 'aa' , t = 'ab'

    ,在建立過字母映射

    a <==> a

    後,s第二個字母 a 其映射

    value = a

    不等于 t 中第二個字母 b
  • s = 'ab' , t = 'aa'

    a <==> b

    後,t第二個字母 a 其映射

    key = a

    不等于s中第二個字母 b

是以這個可以用兩個哈希映射驗證上述兩種情況,也可以用一個映射加判斷是否存在于其 values 中。

​ 既然是建立映射字元,那麼最先想到的就是哈希映射(map、dict)了。

​ 該題為英文單詞字元串同構檢測,整個 ASCll 碼長度才256,是以這道題也可以用

char[256]

以索引值對應一個字元,其存儲值對應一個字元建立映射關系。

還有一個更巧妙的解法,每個字元都與該字元串中第一次出現的索引對比是否相等,判斷是否同構。如:

輸入:s = 'aa' , t = 'ab'
第一次周遊:
s中第一個字元 a 第一次出現的索引為0,t中第一個字元 a 第一次出現的索引為0,索引相等,繼續周遊
第二次周遊:
s中第二個字元 a 第一次出現的索引為0,t中第二個字元 b 第一次出現的索引為1,索引不相等, 傳回false           

代碼:

雙哈希映射:

Java:

class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> s_map = new HashMap<>();
        Map<Character, Character> t_map = new HashMap<>();
        char[] s_chars = s.toCharArray(), t_chars = t.toCharArray(); // 轉成 cahr 型數組
        for (int i = 0; i < s_chars.length; i++) {
            // 兩種不成立的情況
            if (s_map.containsKey(s_chars[i]) && s_map.get(s_chars[i]) != t_chars[i]) return false;
            if (t_map.containsKey(t_chars[i]) && t_map.get(t_chars[i]) != s_chars[i]) return false;
            s_map.put(s_chars[i], t_chars[i]);
            t_map.put(t_chars[i], s_chars[i]);
        }
        return true;
    }
}           

Python:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        s_map, t_map = {}, {} # 雙字典
        for c1, c2 in zip(s, t):
            # 兩種不成立的情況
            if c1 in s_map and s_map[c1] != c2:
                return False
            if c2 in t_map and t_map[c2] != c1:
                return False
            s_map[c1] = c2
            t_map[c2] = c1
        return True           

單哈希映射:

class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> map = new HashMap<>();// 一個哈希映射
        char[] s_chars = s.toCharArray(), t_chars = t.toCharArray();
        for (int i = 0; i < s_chars.length; i++) {
            if (map.containsKey(s_chars[i]) && map.get(s_chars[i]) != t_chars[i]) return false;
            // 判斷t中字元是否存在于映射中的 values 内
            if (!map.containsKey(s_chars[i]) && map.containsValue(t_chars[i])) return false;
            map.put(s_chars[i], t_chars[i]);
        }
        return true;
    }
}           
class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        hash_map = {}
        for c1, c2 in zip(s, t):
            if c1 in hash_map and hash_map[c1] != c2:
                return False
            # 判斷t中字元是否存在于映射中的 values 内
            if c1 not in hash_map and c2 in hash_map.values():
                return False
            hash_map[c1] = c2
        return True           

字元首次出現的索引對比法:

Java:

class Solution {
    public boolean isIsomorphic(String s, String t) {
        char[] s_chars = s.toCharArray();
        char[] t_chars = t.toCharArray();
        for (int i = 0; i < s.length(); i++) {
            // 判斷該字元首次出現索引值是否相等
            if (s.indexOf(s_chars[i]) != t.indexOf(t_chars[i])) {
                return false;
            }
        }
        return true;
    }
}           

Python:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        for c1, c2 in zip(s, t):
            # 判斷該字元首次出現索引值是否相等
            if s.find(c1) != t.find(c2):
                return False
        return True           

256位字元映射

Java

class Solution {
    public boolean isIsomorphic(String s, String t) {
        char[] s_chars = s.toCharArray(), t_chars = t.toCharArray();
        char[] s_map = new char[256], t_map = new char[256]; //索引與存儲值建立映射
        for (int i = 0; i < s_chars.length; i++) {
            char sc = s_chars[i], tc = t_chars[i];
            if (s_map[sc] == 0 && t_map[tc] == 0) {
                s_map[sc] = tc;
                t_map[tc] = sc;
            } else if (s_map[sc] != tc || t_map[tc] != sc) {//索引與元素值的映射是否滿足條件
                return false;
            }
        }
        return true;
    }
}           

python中沒有字元這一基礎資料

歡迎關注微。信。公。衆。号:愛寫Bug