难度: 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:
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
Note:
You may assume both s and t have the same length.
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******
题目已经说了s和t的长度相等了,所以不用考虑
用dictionary记录下对应的映射,但是只能单方面限制,所以我们要同时确保s 和 t 是isomorphic,t 和 s 也是isomorphic
beats 67.95%
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def isoHelper(s1, s2):
lookup = {}
for i, c in enumerate(s1):
if s2[i] in lookup:
if c != lookup[s2[i]]:
return False
else:
lookup[s2[i]] = c
return True
return isoHelper(s, t) and isoHelper(t, s)
思路 2 - 时间复杂度: O(N)- 空间复杂度: O(N)******
一行版本,beats 99.36%
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return len(set(zip(s,t))) == len(set(s)) == len(set(t))