寫一個方法判斷給定的字串是否同態(isomorphic)

王铁柱6發表於2024-11-25
/**
 * 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:

  1. Handles Empty Strings: The code now correctly handles empty strings as isomorphic.

  2. Two Maps for Bijective Mapping: The crucial improvement is the use of two maps: sMap and tMap. 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).

  3. Clearer Variable Names: sChar and tChar improve readability.

  4. 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 in s to characters in t.
  • tMap: Stores mappings from characters in t to characters in s.

For each character pair:

  1. It checks if the character from s already exists as a key in sMap.

    • 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.
  2. 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.

相關文章