205. Isomorphic Strings
給定兩個字符串 s 和 t,判斷它們是否同構。
如果字符串 s 中的字符可以被替換為獲得字符串 t,那麼這兩個字符串 s 和 t 就是同構的。
所有出現的字符必須被替換成另一個字符,同時保持字符的順序。不能有兩個字符映射到同一個字符,但一個字符可以映射到它自己。
範例 :
輸入:s = "egg", t = "add"
輸出:true
Python
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
# Create two dictionaries to store character mappings
s_to_t = {}
t_to_s = {}
for char_s, char_t in zip(s, t):
# Check if there is a mapping in s_to_t
if char_s in s_to_t:
if s_to_t[char_s] != char_t:
return False
else:
s_to_t[char_s] = char_t
# Check if there is a mapping in t_to_s
if char_t in t_to_s:
if t_to_s[char_t] != char_s:
return False
else:
t_to_s[char_t] = char_s
return True
16.58MB, 25ms
C++
class Solution {
public:
bool isIsomorphic(string s, string t) {
// If the lengths of the strings are not the same, they cannot be isomorphic
if (s.size() != t.size()) {
return false;
}
// Create two hash maps to store character mappings
unordered_map<char, char> s_to_t;
unordered_map<char, char> t_to_s;
for (int i = 0; i < s.size(); ++i) {
char char_s = s[i];
char char_t = t[i];
// Check if there is a mapping in s_to_t
if (s_to_t.find(char_s) != s_to_t.end()) {
if (s_to_t[char_s] != char_t) {
return false;
}
} else {
s_to_t[char_s] = char_t;
}
// Check if there is a mapping in t_to_s
if (t_to_s.find(char_t) != t_to_s.end()) {
if (t_to_s[char_t] != char_s) {
return false;
}
} else {
t_to_s[char_t] = char_s;
}
}
return true;
}
};
9.66MB, 10ms
Javascript
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isIsomorphic = function(s, t) {
if (s.length !== t.length) {
return false;
}
// Create two maps to store character mappings
const sToT = new Map();
const tToS = new Map();
for (let i = 0; i < s.length; i++) {
const charS = s[i];
const charT = t[i];
// Check if there is a mapping in sToT
if (sToT.has(charS)) {
if (sToT.get(charS) !== charT) {
return false;
}
} else {
sToT.set(charS, charT);
}
// Check if there is a mapping in tToS
if (tToS.has(charT)) {
if (tToS.get(charT) !== charS) {
return false;
}
} else {
tToS.set(charT, charS);
}
}
return true;
};
50.54MB, 56ms