Day039 - 205. Isomorphic Strings
업데이트:
205. Isomorphic Strings
Given two strings s
and t
, determine if they are isomorphic.
Two strings s
and t
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 Explanation: The strings
s
andt
can be made identical by:
- Mapping
'e'
to'a'
.- Mapping
'g'
to'd'
.
Example 2:
Input: s = “foo”, t = “bar” Output: false Explanation: The strings
s
andt
can not be made identical as'o'
needs to be mapped to both'a'
and'r'
.
Example 3:
Input: s = “paper”, t = “title” Output: true
Constraints:
1 <= s.length <= 5 * 104
t.length == s.length
s
andt
consist of any valid ascii character.
내 풀이
from collections import defaultdict
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(set(s)) != len(set(t)): return False
s_checker = defaultdict(list)
t_checker = defaultdict(list)
current_idx = 0
s_same = False
t_same = False
for s_one, t_one in zip(s, t):
if (s_one in s_checker) != (t_one in t_checker):
return False
if current_idx >= 1:
s_same = s_one == s[current_idx-1]
t_same = t_one == t[current_idx-1]
if s_same != t_same:
return False
if s_checker[s_one] != t_checker[t_one]:
return False
s_checker[s_one].append(current_idx)
t_checker[t_one].append(current_idx)
current_idx += 1
return True
# Time Complexity : \(O(N)\)
댓글남기기