728x90
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
s2t, t2s = {}, {}
for p, w in zip(s, t):
if w not in s2t and p not in t2s:
s2t[w] = p
t2s[p] = w
elif w not in s2t or s2t[w] != p:
# Contradict mapping.
return False
return True
서로 상대방의 string을 key와 value로 map 한다.
elif 문
w(p의 char)가 s의 dict인 s2t에 없거나(처음 보는 다른 char일 경우)
s2t의 key는 있지만 (t의 char이 s에 있지만, 즉 기존에 mapped 되었지만), 새로운 char가 등장한 경우
출처: github.com/jiapengwen/LeetCode/blob/master/Python/isomorphic-strings.py
---
같은 의미 다른 코드
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_map = {}
t_map = {}
for i in range(0,len(s)):
s_ch = s[i]
t_ch = t[i]
if s_ch not in s_map:
s_map[s_ch] = t_ch
if t_ch not in t_map:
t_map[t_ch] = s_ch
if s_map[s_ch] != t_ch or t_map[t_ch] != s_ch:
return False
return True
s_map, t_map으로 dict 생성
s_map의 key는 s의 char, value는 t의 char
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Contains Duplicate II 파이썬 (dict) (0) | 2021.04.05 |
---|---|
[LeetCode] Reverse Linked List 파이썬 (0) | 2021.04.05 |
[LeetCode] Count Primes 파이썬 (0) | 2021.04.04 |
[LeetCode] Remove Linked List Elements 파이썬 (linked list) (0) | 2021.04.04 |
[LeetCode] Happy Number 파이썬 (dict, cycle) (0) | 2021.04.04 |
댓글