leetcode python3 简单题205. Isomorphic Strings

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第二百零五题

(1)题目
英文:
Given two strings s and t, determine if they are isomorphic.

Two strings 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.

中文:
给定两个字符串 s 和 t,判断它们是否是同构的。

如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。

所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/isomorphic-strings

(2)解法
① 对于同构字符串,两个字符串中第一个出现的字符对应的index必须相同。
(耗时:48ms,内存:14.3M)

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        return [*map(s.index, s)] == [*map(t.index, t)]

注意:
1.map输出输出的是一个对象地址,如果要输出具体的数值,则可以使用:
① *map(…),也可以外加一个[],输出列表
② list(map(…)),直接输出列表

② 使用dict,分情况讨论,这个的流程和题目介绍的流程相似
(耗时:44ms,内存:13.9M)

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        dic = {}
        s = list(s)
        t = list(t)
        for i in range(len(s)):
            if t[i] not in dic:
                dic[t[i]] = s[i]
        if len(dic.values()) != len(set(dic.values())):
            return False
        for i in range(len(s)):
            t[i] = dic[t[i]]         
        return t == s

注意:
1.分情况讨论详述:
① 首先:

for i in range(len(s)):
            if t[i] not in dic:
                dic[t[i]] = s[i]

这段是拿到t和s中第一次出现字符的对应关系,如果t中字符已有出现在dic中,则不会新添加了,这样可以限制后面只有是同构的情况才能使t==s,也就是t中有字符重复几次,s中的相应位置的字符也要重复几次,否则t!=s

② 然后:
如果dic中有重复的value,则表明s中有重复字符,而在t中没有对应着重复,直接输出False

③ 如果②是满足的,则通过下面代码来判断s中的重复模式是否与t相同,如果相同,则输出True

猜你喜欢

转载自blog.csdn.net/qq_37285386/article/details/106083631