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.
풀이
처음에 문제를 보고 이해를 하지 못해서 다른 문제 LeetCode 290. Word Pattern 을 풀고나서 다시 돌아와서 봤는데.
문제가 거의 비슷하다는걸 알았다.
전의 코드로 제출하니 통과가 되었다, 메모리가 다른사람보다 많이 먹는 거같아서 전에 봤던 다른사람의 코드를 find 활용해서 풀어봤다.
1. 딕셔너리 (해시맵 사용)
class Solution(object):
def isIsomorphic(self, s, t):
dict1 ={}
dict2 ={}
if len(s) != len(t):
return False
for p,w in zip(s,t):
if p not in dict1 and w not in dict2:
dict1[p] = w
dict2[w] = p
elif p in dict1 and w in dict2:
if dict1[p] != w or dict2[w] != p:
return False
else:
return False
return True
2. find로 각 인덱스가 같은 위치를 가르키는지 확인하는 코드
class Solution(object):
def isIsomorphic(self, s, t):
if len(s) != len(t): # 둘의 개수가 같은지 확인
return False
for i in range(len(s)):
if s.find(s[i]) != t.find(t[i]): # find함수로 각 인덱스의 위치가 동일한 위치를 짚는지 확인
return False
return True
find와 index 둘 다 사용 가능하다, 인덱스 위치를 찾을떄 가르키는 방향이 같은 곳인지 확인해주면 된다.-> 되는 이유: find함수는 index(인자) 를 통해서 인자의 인덱스 위치를 찾게되는데, 가르키는 위치가 다른 곳에 있거나 존재하지 않는다면 인덱스의 값이 동일하지 않기에 틀린지 옳은지 찾을 수 있다.
'알고리즘 > LeetCode' 카테고리의 다른 글
153. Find Minimum in Rotated Sorted Array (0) | 2023.09.05 |
---|---|
LeetCode 162.Find Peak Element (0) | 2023.09.05 |
LeetCode 202. Happy Number (0) | 2023.09.01 |
49. Group Anagrams (0) | 2023.09.01 |
LeetCode 290. Word Pattern (0) | 2023.09.01 |