[LeetCode]#205. Isomorphic Strings

Fatboy Slim
1 min readMar 21, 2020

--

Environment: Python 3.7

Key technique: Counter,[[‘a’, ‘a’], [‘a’, ‘a’]]

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

Analysis:

We can see “e”, “g”, “g”, that have their pair “a”, “d”, “d” and it get True. In the other, “o” can’t get pair due to it maps to “a” and “r”.

Solution:

from collections import Counter
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
sc=len(Counter(s))
st=len(Counter(t))
if(sc!=st):
return False
else:
s1=[]
t1=[]
m=[]
ans=[]
for i in s:
s1.append(i)
for i in t:
t1.append(i)
m.append(s1)
m.append(t1)
for i in s:
if i in m[0]:
a=m[0].index(i)
ans.append(m[1][a])

return "".join(ans) == t

Submitted result:

Lesson learn:

The Counter can fix the bug “aa” , “ab” this special case.

Reference:

https://leetcode.com/problems/isomorphic-strings/discuss/524279/Python-solution(Not-the-quickest-but-still-readable)

--

--