Daily LeetCode 205. Isomorphic Strings

https://leetcode.com/problems/isomorphic-strings/

Easy

问题描述:

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.

Example 1:

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

Example 2:

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

Example 3:

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

Note:
You may assume both s and t have the same length.

题目分析:

给定字符串st,我们需要判断两个字符串的结构是否相同,即它们是不是同构的。

我看到这一题最初的思路是分别处理st,将字符串转换为数字的形式,拿例1来说,将s转换成011t也转换成011,两个数字相等,那么两个字符串就是同构的,但这种解决方法会导致超时。

另一个解题思路就是从一个字符串入手,找该字符串和另一个字符串之间的联系。我们可以建立一个字典,来建立从字符串s到字符串t的映射。

拿例3来说,我们设置一个字典dict_tmp,遍历s,如果当前ith字符ch不在字典中,我们先查看是否存在s->t的映射,若已经存在,那么说明不是同构,因为我们要确保映射的一一对应;若不存在,我们就将dict_tmp[ch]设置为t[i]

如果当前字符在字典中,则说明该字符在之前的遍历过程中已经出现过,这时我们需要判断t中对应位置上的字符是否与上次记录的字符相同,即dict_tmp[ch]是否等于t[i],若不相同,则说明两个字符串不是同构的。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
dict_tmp = {}
for index, ch in enumerate(s):
if ch in dict_tmp:
if dict_tmp[ch] != t[index]:
return False
elif t[index] in dict_tmp.values():
return False
else:
dict_tmp[ch] = t[index]
return True