https://leetcode.com/problems/isomorphic-strings/
Isomorphic Strings - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
상당히 낯선 단어인데 Isomorphic은 동형사상이라는 뜻이라고 합니다.
Isomorphic String은 두 String의 형태가 닮아있는 것을 말하는데요. 예를 들어 glass와 shell이 동형관계입니다.
두 단어는 생김새가 전혀 다르지만 알파벳이 등장하는 순서대로 번호를 매기면 12344, 12344로 구조가 같음을 알 수 있습니다.
반대로 banana와 canada는 단어 생긴건 비슷하지만 번호를 매기면 123232와 123242로 차이가 있습니다.
문제에서 주어진 String을 앞에서부터 읽어가며 처음 만나는 알파벳인 경우 Dictionary에 Index값을 넣어주고, 이미 만났던 알파벳인 경우 Index값을 비교해 같은 구조인지 체크해줬습니다.
물론 알파벳의 내용은 다르므로 Dictionary를 두개 만들어서 따로 저장했습니다.
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
sDict = {}
tDict = {}
idx = 0
for i in range(0,len(s)):
if(not (s[i] in sDict) and not (t[i] in tDict)):
sDict[s[i]] = idx
tDict[t[i]] = idx
idx += 1
elif(s[i] in sDict and t[i] in tDict):
if(sDict[s[i]] != tDict[t[i]]):
return False
else:
return False
return True
input = [["egg","add"],["foo","bar"],["paper","title"]]
for i in input:
print(Solution().isIsomorphic(i[0],i[1]))
728x90
'🔍 알고리즘 > Leetcode' 카테고리의 다른 글
[Python] Leetcode 509. Fibonacci Number (Easy) (0) | 2022.07.22 |
---|---|
[Python] Leetcode 392. Is Subsequence (Easy) (0) | 2022.07.22 |
[Python] Leetcode 724. Find Pivot Index (Easy) (0) | 2022.07.21 |
[Python] Leetcode 1480. Running Sum of 1d Array (Easy) (0) | 2022.07.21 |
[Python] Leetcode 13. Roman to Integer (Easy) (0) | 2022.07.21 |