Edit: For an even shorter solution, check out mathsam's answer below and my comment on it.
class Solution:
def isIsomorphic(self, s, t):
return all(map({}.setdefault, a, b) == list(b) for a, b in ((s, t), (t, s)))
Oh wow, that's neat. And can be improved further:
def isIsomorphic(self, s, t):
return map(s.find, s) == map(t.find, t)
There's a catch, though. It's quadratic in time. For example, consider 'a' * n + 'b' * n
, where find
needs to go through the n 'a'
characters for every one of the n 'b'
characters. But apparently the online judge doesn't have such a case, as I got this accepted in 64 ms.
A good mix of the two approaches is this:
def isIsomorphic(self, s, t):
f = lambda s: map({}.setdefault, s, range(len(s)))
return f(s) == f(t)
Could be turned into a one-liner, but I wasn't able to do so in a nice way.
@jain98 No, it needs one or two. But it always does get two here, so I don't know what you mean.