2023年5月22日 星期一

5/22 每日一題(創造同構的字串)

 205. Isomorphic Strings

Easy
6.7K
1.5K
Companies

Given two strings s and tdetermine if they 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.

 

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

 

Constraints:

  • 1 <= s.length <= 5 * 104
  • t.length == s.length
  • s and t consist of any valid ascii character.

#注意, 這邊禁止兩個字元對映到相同的字元  只能1對1  不能 多對一

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        """No two characters may map to the same characte"""
        letter_dict={}
        new_str=''
        for i in range(len(s)):
            if s[i] not in letter_dict.keys() :    
                if t[i] not in letter_dict.values():
                    letter_dict[s[i]]=t[i] #創造對映字典
                else:
                    #出現多對一情況
                    letter_dict[s[i]]='_'

            new_str += letter_dict[s[i]]
       
        return t == new_str
---------------------------------------
參考解答

  1. 可以使用两个列表或数组来存储字符的映射关系,而不是使用字典。这样可以提供更好的性能,因为在列表或数组中访问元素比在字典中访问元素更快。

  2. 可以简化逻辑,直接检查两个字符串中对应位置的字符是否相同。如果不相同,可以立即返回 False。

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        s_to_t = [None] * 256  # 用于存储 s 中字符到 t 中字符的映射关系
        t_mapped = [False] * 256  # 用于追踪已经映射过的 t 中字符

        for i in range(len(s)):
            s_char = ord(s[i])  # 将字符转换为 ASCII 值
            t_char = ord(t[i])

            if s_to_t[s_char] is None:
                if t_mapped[t_char]:
                    return False  # s 中的多个字符映射到 t 中的同一个字符

                s_to_t[s_char] = t_char
                t_mapped[t_char] = True
            else:
                if s_to_t[s_char] != t_char:
                    return False  # s 中的字符与 t 中的字符不对应

        return True
-------------------------------------------------


標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁