写一个方法判断给定的字符串是否同态(isomorphic)
/**
* Checks if two strings 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.
*
* @param {string} s The first string.
* @param {string} t The second string.
* @return {boolean} True if the strings are isomorphic, false otherwise.
*/
function isIsomorphic(s, t) {
if (s.length !== t.length) {
return false;
}
const sMap = new Map();
const tMap = new Map();
for (let i = 0; i < s.length; i++) {
const sChar = s[i];
const tChar = t[i];
if (!sMap.has(sChar)) {
sMap.set(sChar, tChar);
} else if (sMap.get(sChar) !== tChar) {
return false;
}
if (!tMap.has(tChar)) {
tMap.set(tChar, sChar);
} else if (tMap.get(tChar) !== sChar) {
return false;
}
}
return true;
}
// Example usage:
console.log(isIsomorphic("egg", "add")); // true
console.log(isIsomorphic("foo", "bar")); // false
console.log(isIsomorphic("paper", "title")); // true
console.log(isIsomorphic("badc", "baba")); // false 'a' maps to both 'a' and 'b' in t
console.log(isIsomorphic("", "")); // true - Empty strings are considered isomorphic
console.log(isIsomorphic("ab", "ca")); //true
Explanation and Improvements:
-
Handles Empty Strings: The code now correctly handles empty strings as isomorphic.
-
Two Maps for Bijective Mapping: The crucial improvement is the use of two maps:
sMap
andtMap
. This ensures a one-to-one (bijective) mapping between characters. The original approach with a single map could lead to incorrect results (e.g., "badc" and "baba" would have been considered isomorphic with a single map). -
Clearer Variable Names:
sChar
andtChar
improve readability. -
JSDoc Comments: Added JSDoc style comments to clearly explain the function's purpose and parameters.
How it works (with the two maps):
sMap
: Stores mappings from characters ins
to characters int
.tMap
: Stores mappings from characters int
to characters ins
.
For each character pair:
-
It checks if the character from
s
already exists as a key insMap
.- If it doesn't, it adds the mapping (sChar -> tChar).
- If it does, it verifies that the existing mapped value matches the current
tChar
. If not, the strings are not isomorphic.
-
It performs the same check using
tMap
(tChar -> sChar).
This two-way check ensures that no two characters in s
map to the same character in t
and vice-versa, enforcing the isomorphism condition.
This improved version is more robust and accurately determines string isomorphism. It addresses the potential flaw in the single-map approach.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现