LeetCode 205:同構字符串 Isomorphic Strings

題目:

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

若是 s 中的字符能夠被替換獲得 *t* ,那麼這兩個字符串是同構的。python

全部出現的字符都必須用另外一個字符替換,同時保留字符的順序。兩個字符不能映射到同一個字符上,但字符能夠映射本身自己。數組

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

Two strings are isomorphic if the characters in *s* can be replaced to get *t*.spa

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.code

示例 1:cdn

輸入: s = "egg", t = "add"
輸出: true
複製代碼

示例 2:索引

輸入: s = "foo", t = "bar"
輸出: false
複製代碼

示例 3:ip

輸入: 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
複製代碼

單哈希映射:

Java:

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;
    }
}
複製代碼

Python:

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.png

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

相關文章
相關標籤/搜索